程序等效默认(类型)

程序等效默认(类型)

我使用反射循环通过一个Type属性,并将某些类型设置为默认类型。default(Type)很明显,但我宁愿用一行来做。是否有相当于默认程序的程序?



手掌心
浏览 423回答 3
3回答

皈依舞

在值类型使用的情况下Activator.CreateInstance它应该能正常工作。当使用引用类型时,只需返回NULLpublic static object GetDefault(Type type){    if(type.IsValueType)    {       return Activator.CreateInstance(type);    }    return null;}在较新版本的.net中,如.net标准,type.IsValueType需要写成type.GetTypeInfo().IsValueType

小怪兽爱吃肉

为什么不调用使用反射返回默认值(T)的方法?您可以使用任何类型的GetDefault:&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;object&nbsp;GetDefault(Type&nbsp;t) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this,&nbsp;null); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;T&nbsp;GetDefaultGeneric<T>() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;default(T); &nbsp;&nbsp;&nbsp;&nbsp;}

杨__羊羊

你可以用PropertyInfo.SetValue(obj, null)..如果调用一个值类型,它将为您提供缺省值。此行为已记录在案。在.NET 4.0中和在.NET 4.5中.
打开App,查看更多内容
随时随地看视频慕课网APP