简体   繁体   English

如何将System.Reflection.PropertyInfo对象转换为其原始对象类型

[英]How to convert System.Reflection.PropertyInfo object to its original object type

Um looking for a way to convert a System.Reflection.PropertyInfo to its original object 嗯正在寻找一种方法将System.Reflection.PropertyInfo转换为其原始对象

 public static Child ConvertToChiildObject(this PropertyInfo propertyInfo)
    {
        var p = (Child)propertyInfo;

    }

The propertyInfo object actulayy holds a class like this propertyInfo对象actulayy拥有这样的类

public class Child{
  public string name = "S";
  public string age = "44";

}

So far I have tried implicit casting Is there a way to do this? 到目前为止,我已经尝试过隐式转换有没有办法做到这一点?

I must preface that this is not an answer to the question but an education excersise. 我必须断言,这不是问题的答案,而是教育的优点。

As others have explained you are misunderstanding the usage of the PropertyInfo class. 正如其他人所解释的那样,你误解了PropertyInfo类的用法。 This class is used to describe the property and does not contain and instance related data. 此类用于描述属性, 包含与实例相关的数据。 Therefore what you are trying to do is not possible without some additional information provided. 因此,如果没有提供一些额外的信息,您无法实现的目标。

Now the PropertyInfo class can get the instance related data from an object but you must have an instance of the object to read the data from. 现在, PropertyInfo可以从对象获取与实例相关的数据,但您必须具有该对象的实例才能从中读取数据。

For example, take the following class structure. 例如,采用以下类结构。

public class Child
{
    public string name = "S";
    public string age = "44";
}

public class Parent
{
    public Parent()
    {
        Child = new Child();
    }

    public Child Child { get; set; }
}

The property Child is a property of the Parent class. 属性ChildParent类的属性。 When the parent class is constructed a new Child instance is created as part of the Parent instance. 构造父类时,将创建一个新的Child实例作为Parent实例的一部分。

We can then use Reflection to get the value of the property Child by simply calling. 然后我们可以使用Reflection通过简单调用来获取属性Child的值。

var parent = new Parent();
var childProp = typeof(Parent).GetProperty("Child");
var childValue = (Child)childProp.GetValue(parent);

This works just fine. 这很好用。 The important part is (Child)childProp.GetValue(parent) . 重要的部分是(Child)childProp.GetValue(parent) Note that we are accessing the GetValue(object) method of the PropertyInfo class to retrieve the value of the Child property from the instance of the Parent class. 请注意,我们正在访问PropertyInfo类的GetValue(object)方法,以从Parent类的实例中检索Child属性的值。

This is fundementally how you would have to design the method for accessing the property data. 这很有趣,你必须设计访问属性数据的方法。 However as we have listed a few times you must have an instance of the property. 但是,由于我们已经列出了几次,您必须拥有该属性的实例。 Now we can write an extension method that will faciliate this call. 现在我们可以编写一个可以促进此调用的扩展方法。 As I see it there is no advantage to use an extension method as the existing PropertyInfo.GetValue(object) method is quite quick to use. 我认为使用扩展方法没有任何优势,因为现有的PropertyInfo.GetValue(object)方法使用起来非常快。 However if you would like to create a new instance of the parent object then get the value then you could write a very simply extension method. 但是,如果您想创建父对象的新实例然后获取值,那么您可以编写一个非常简单的扩展方法。

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);

}

Now this extension method simply accepts an instance as a second parameter (or first in the extension call). 现在,此扩展方法只接受一个实例作为第二个参数(或扩展调用中的第一个参数)。

var parent = new Parent();
parent.Child.age = "100";
var childValue = childProp.ConvertToChildObject<Parent, Child>(parent);
var childValueNull = childProp.ConvertToChildObject<Parent, Child>(null);

Results 结果

childValue = name: S, age: 44
childValueNull = name: S, age: 100

Note the importance of having an instance. 请注意拥有实例的重要性。

One Caveat : The extension method will create a new instance of the object if the object is null by calling: 一个警告 :如果对象为null,则扩展方法将通过调用以下方法创建对象的新实例:

if (instance == null)
    instance = Activator.CreateInstance<TInstanceType>();

You will also notice the typeparam TInstanceType must be a class and must confirm to the new() restriction. 您还会注意到typeparam TInstanceType必须是一个class并且必须确认new()限制。 This means it must be a class and must have a parameterless constructor. 这意味着它必须是一个class并且必须具有无参数构造函数。

I understand this isn't a solution to the question, but hope it helps. 我知道这不是问题的解决方案,但希望它有所帮助。

Try this: 尝试这个:

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; 
}

In the above, I used the extra parameter parent which is the base object of the Child . 在上面,我使用了额外的参数parent ,它是Child的基础对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将类型&#39;System.Reflection.PropertyInfo&#39;转换为 - Cannot convert type 'System.Reflection.PropertyInfo' to 如何提取 class object 的 System.Reflection.PropertyInfo 名称作为 csv 文件的第一行 - How to extract System.Reflection.PropertyInfo names of a class object as first row of a csv file 转换表达式数组 <Func<TModel, object> &gt; []到列表列表 <System.Reflection.PropertyInfo> - Converting array of Expression<Func<TModel, object>>[] to list of List<System.Reflection.PropertyInfo> 如何创建列表 <unknown type at compile time> 并通过System.Reflection.PropertyInfo复制项目 - How to create a List<unknown type at compile time> and copy items via System.Reflection.PropertyInfo 如何最好地处理system.reflection.propertyInfo NULLReferenceExceptions - how to best handle system.reflection.propertyInfo NULLReferenceExceptions 'System.String' 类型的表达式不能用于'System.Reflection.PropertyInfo' 类型的参数 - 'Expression of type 'System.String' cannot be used for parameter of type 'System.Reflection.PropertyInfo' C# - 将Reflection.PropertyInfo对象转换为其Type - C# - Casting a Reflection.PropertyInfo object to its Type 运算符&#39;==&#39;不能应用于操作数System.Reflection.PropertyInfo和&#39;int&#39; - Operator '==' cannot be applied to operands System.Reflection.PropertyInfo and 'int' 反思:如何通过 PropertyInfo 获取类对象 - Reflection: How to get the class object via PropertyInfo 如何使用反射将 PropertyInfo 转换为自己的类型 - How to cast PropertyInfo to its own type using reflection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM