我想知道下面的语句是否曾经为参考类型返回不同的结果,还是它们是相同的?默认(T)与Activator.CreateInstance(T)
如果它们是相同的,可以总是使用默认值(T),在此实例中,如果目的是要输出的T?:
的默认值if (typeof(T).IsValueType || typeof(T) == typeof(String))
{
return default(T);
}
else
{
return Activator.CreateInstance<T>();
}
Best way to test if a generic type is a string? (c#)
TA!
不,引用类型的默认值(T)返回null,CreateInstance()不会产生,因为它创建了一个类型为T的对象。很难猜测这段代码真的尝试了什么做。 –
也不是'default(string)'null吗? – BoltClock
谢谢你澄清混淆!代码示例是混淆的一部分,我在它下面链接的stackoverflow帖子中看到它。 – Cel