Activator.CreateInstance 返回 null

wea*_*ver 0 c# reflection unity-game-engine

我有这么一小段代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

问题是我得到了 NULL Reference Exception,但我不知道为什么。

AyC*_*yCe 5

x as T切勿在您期望x的时候使用T。在这种情况下,请务必使用(T) x代替。这样,您就可以尽早发现对象类型错误的错误,而不是将其隐藏起来NullReferenceExceptions