嗯,正在寻找一种将 System.Reflection.PropertyInfo 转换为其原始对象的方法
public static Child ConvertToChiildObject(this PropertyInfo propertyInfo)
{
var p = (Child)propertyInfo;
}
propertyInfo 对象 actulayy 拥有这样一个类
public class Child{
public string name = "S";
public string age = "44";
}
到目前为止,我已经尝试过隐式转换 有办法做到这一点吗?
最佳答案
我必须先声明,这不是问题的答案,而是教育练习。
正如其他人所解释的,您误解了 PropertyInfo
类的用法。此类用于描述属性,不包含与实例相关的数据。因此,如果不提供一些额外的信息,您将无法完成您想要做的事情。
现在 PropertyInfo
类可以从对象中获取与实例相关的数据,但您必须有一个对象实例才能从中读取数据。
例如,采用以下类结构。
public class Child
{
public string name = "S";
public string age = "44";
}
public class Parent
{
public Parent()
{
Child = new Child();
}
public Child Child { get; set; }
}
属性 Child
是 Parent
类的属性。构造父类时,将创建一个新的 Child
实例作为 Parent
实例的一部分。
然后我们可以使用 Reflection
通过简单地调用来获取属性 Child
的值。
var parent = new Parent();
var childProp = typeof(Parent).GetProperty("Child");
var childValue = (Child)childProp.GetValue(parent);
这很好用。重要的部分是 (Child)childProp.GetValue(parent)
。请注意,我们正在访问 PropertyInfo
类的 GetValue(object)
方法,以从 实例中检索 Child
属性的值 Parent
类。
从根本上说,您必须如何设计访问属性数据的方法。但是,正如我们多次列出的那样,您必须拥有该属性的一个实例。现在我们可以编写一个扩展方法来简化此调用。正如我所见,使用扩展方法没有任何优势,因为现有的 PropertyInfo.GetValue(object)
方法使用起来非常快。但是,如果您想创建父对象的新实例然后获取值,那么您可以编写一个非常简单的扩展方法。
public static TPropertyType ConvertToChildObject<TInstanceType, TPropertyType>(this PropertyInfo propertyInfo, TInstanceType instance)
where TInstanceType : class, new()
{
if (instance == null)
instance = Activator.CreateInstance<TInstanceType>();
//var p = (Child)propertyInfo;
return (TPropertyType)propertyInfo.GetValue(instance);
}
现在这个扩展方法只接受一个实例作为第二个参数(或扩展调用中的第一个参数)。
var parent = new Parent();
parent.Child.age = "100";
var childValue = childProp.ConvertToChildObject<Parent, Child>(parent);
var childValueNull = childProp.ConvertToChildObject<Parent, Child>(null);
结果
childValue = name: S, age: 44
childValueNull = name: S, age: 100
注意实例的重要性。
一个警告:如果对象为 null,扩展方法将通过调用创建对象的新实例:
if (instance == null)
instance = Activator.CreateInstance<TInstanceType>();
您还会注意到 typeparam
TInstanceType
必须是 class
并且必须向 new()
确认限制。这意味着它必须是一个类
并且必须有一个无参数构造函数。
我知道这不是问题的解决方案,但希望它能有所帮助。
关于c# - 如何将 System.Reflection.PropertyInfo 对象转换为其原始对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34670236/