我希望创建一个变量X,X的值为【string】这一类型、或其他类型。我该怎么写?【Type X=string;】会报错。
我之所以需要它,是因为Unity中有如下两个内容:
GetComponent<HorizontalLayoutGroup>
GetComponent<VerticalLayoutGroup>
我要定义一个布局类,每次都需要因为这两个东西而分类讨论,很麻烦。
我希望写成:
X=HorizontalLayoutGroup;
GetComponent<X>
我该怎么做?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
System.Type x = typeof(HorizontalLayoutGroup);
Component component = GetComponent(x);
}
// Update is called once per frame
void Update()
{
}
}
可以利用反射的原理,将字符串转为相应的类对象,就可以了
用Object类型。
Object类是C#中的基类类型,所有的对象都派生于它。
var x = GetComponent<HorizontalLayoutGroup>();
typeof ?