Vic*_*Gil 5 c# generics propertyinfo setvalue visual-studio
好的,所以我正在学习泛型,我正试图让这个东西运行,但它一直在说我同样的错误.这是代码:
public static T Test<T>(MyClass myClass) where T : MyClass2
{
var result = default(T);
var resultType = typeof(T);
var fromClass = myClass.GetType();
var toProperties = resultType.GetProperties();
foreach (var propertyInfo in toProperties)
{
var fromProperty = fromClass.GetProperty(propertyInfo.Name);
if (fromProperty != null)
propertyInfo.SetValue(result, fromProperty, null );
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
这是因为default(T)
回报null
,因为T
代表引用类型.引用类型的默认值是null
.
您可以将方法更改为:
public static T Test<T>(MyClass myClass) where T : MyClass2, new()
{
var result = new T();
...
}
Run Code Online (Sandbox Code Playgroud)
然后它会按你的意愿工作.当然,MyClass2
它的后代现在必须有一个无参数构造函数.
归档时间: |
|
查看次数: |
13626 次 |
最近记录: |