Activator.CreateInstance返回null

时间:2018-10-23 23:08:16

标签: c# unity3d reflection

我有这小段代码:

public static I CreateInstance<I>(string myClassName) where I : class
{
    Debug.Log("Instance: " + (Activator.CreateInstance(null, myClassName) as I));
    return Activator.CreateInstance(null, myClassName) as I;
}

void Test(string testName)
{
    testName = "TestProvider";
    var data = CreateInstance<IProviderInitializer>(testName).GetProviderInfo();
    Debug.Log("Data: " + data);
}

问题是我得到了NULL引用异常,我也不知道为什么。

3 个答案:

答案 0 :(得分:2)

您可以创建一个Type对象并将那个传递给{{3,而不是使用将类型作为字符串的重载(并返回对象的句柄), }}接受Type

Type t = Type.GetType(myClassName);
return Activator.CreateInstance(t) as I;

答案 1 :(得分:1)

来自the Documentation

public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName);

CreateInstance方法调用返回“ ObjectHandle”类型,该类型不能转换为“ I”, Activator.CreateInstance(null, myClassName) as I 将始终返回null。

您需要解开对象

public static void Main()
   {
      ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
      Person p = (Person) handle.Unwrap();
      p.Name = "Samuel";
      Console.WriteLine(p);
   }

答案 2 :(得分:0)

当您期望 x as Tx 时,切勿使用 T。在这种情况下,请始终使用 (T) x。这样您就可以及早发现对象类型错误的错误,而不是将它们隐藏在 NullReferenceExceptions 后面。