嗯正在寻找一种方法将System.Reflection.PropertyInfo转换为其原始对象
public static Child ConvertToChiildObject(this PropertyInfo propertyInfo)
{
var p = (Child)propertyInfo;
}
Run Code Online (Sandbox Code Playgroud)
propertyInfo对象actulayy拥有这样的类
public class Child{
public string name = "S";
public string age = "44";
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试过隐式转换有没有办法做到这一点?
我必须断言,这不是问题的答案,而是教育的优点.
正如其他人所解释的那样,你误解了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; }
}
Run Code Online (Sandbox Code Playgroud)
该物业Child是该Parent类别的财产.构造父类时,将创建一个新Child实例作为Parent实例的一部分.
然后我们可以通过简单地调用Reflection来获取属性的值Child.
var parent = new Parent();
var childProp = typeof(Parent).GetProperty("Child");
var childValue = (Child)childProp.GetValue(parent);
Run Code Online (Sandbox Code Playgroud)
这很好用.重要的是(Child)childProp.GetValue(parent).请注意,我们正在访问类的GetValue(object)方法,PropertyInfo以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);
}
Run Code Online (Sandbox Code Playgroud)
现在,此扩展方法只接受一个实例作为第二个参数(或扩展调用中的第一个参数).
var parent = new Parent();
parent.Child.age = "100";
var childValue = childProp.ConvertToChildObject<Parent, Child>(parent);
var childValueNull = childProp.ConvertToChildObject<Parent, Child>(null);
Run Code Online (Sandbox Code Playgroud)
结果
childValue = name: S, age: 44
childValueNull = name: S, age: 100
Run Code Online (Sandbox Code Playgroud)
请注意拥有实例的重要性.
一个警告:如果对象为null,则扩展方法将通过调用以下方法创建对象的新实例:
if (instance == null)
instance = Activator.CreateInstance<TInstanceType>();
Run Code Online (Sandbox Code Playgroud)
您还会注意到typeparam TInstanceType必须是a class并且必须确认new()限制.这意味着它必须是a class并且必须具有无参数构造函数.
我知道这不是问题的解决方案,但希望它有所帮助.
尝试这个:
public static Child ConvertToChildObject(this PropertyInfo propertyInfo, object parent)
{
var source = propertyInfo.GetValue(parent, null);
var destination = Activator.CreateInstance(propertyInfo.PropertyType);
foreach (PropertyInfo prop in destination.GetType().GetProperties().ToList())
{
var value = source.GetType().GetProperty(prop.Name).GetValue(source, null);
prop.SetValue(destination, value, null);
}
return (Child) destination;
}
Run Code Online (Sandbox Code Playgroud)
在上面,我使用了额外的参数parent,它是的基础对象Child。