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

标签 c# c#-4.0

嗯,正在寻找一种将 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; }
}

属性 ChildParent 类的属性。构造父类时,将创建一个新的 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/

相关文章:

c# - 隐藏asp Repeater的HeaderTemplate

c# - 如何实例化在 C# DLL 中声明的类?

entity-framework - 使用 TextTransform.exe 从 edmx 文件生成代码

javascript - Google Picker => 如何下载文件

c++ - 如何提高我的 C++ 程序读取分隔文本文件的速度?

c# - 如何使用复选框显示/隐藏表单?

javascript - 如何在自动建议文本框中获取所选项目(字符串)的第一个单词(Jquery,c#)

c# - 如何在约束条件下使多个按钮居中?

architecture - 服务层的服务可以互相通信吗?

c# - 使用 C# 和正则表达式解析日志文件