2

我创建了一个动态方法来创建不同类型的实例,但不确定为什么它在编译时给出上述错误,我是否必须再次将返回值转换为指定类型?

 internal static T GetInstance<T>()
    {
        dynamic obj = Activator.CreateInstance(typeof(T));
        return obj;
    }

    private Foo f = GetInstance<Foo>();
4

1 回答 1

7

为什么不直接使用 MSDN 推荐的,如下:

internal static T GetInstance<T>() where T:new()
{
    return new T();
}

http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspx

编辑:

虽然,我不明白为什么你甚至想要这种方法?

而不是调用var x = GetInstance<Foo>();,你可以这样做,var x = new Foo();因为如果你想作为类型参数调用 Foo 必须有无参数构造GetInstance<T>()函数Foo(或者我错过了什么?)。

于 2012-03-14T11:49:54.823 回答