动态检测从不同项目传递的 dll 中的对象属性

本文关键字:dll 对象 属性 检测 项目 动态 | 更新日期: 2023-09-27 18:34:56

我正在构建一个通用用户控件。 这将是一个标签和一个文本框的组合。这将是一个类库项目。

标签和文本框的文本将与外部项目绑定。在我导入 dll 的项目中。

我正在尝试使用户控件完全通用。例如,我会将任何对象和对象的属性名称发送到 dll。DLL 将读取对象,获取对象属性,获取发送参数的值,并在 WIN 窗体中充当另一个就绪控件。

myControl1.DataBindings.Add("DataSource",object,"PropertyName1");

只需这样说,myController1 将获取与PropertyName1 object关联的值,并将值与文本框和标签绑定。

动态检测从不同项目传递的 dll 中的对象属性

你想为此使用反射。这就是使用扩展方法执行此操作的方式,但是如果需要,可以轻松地将其设置为常规函数。我试图解释它用评论做什么。

    public static T GetProperty<T>(this object obj, string name)
    {
        Type type = obj.GetType(); // Get the object's type
        PropertyInfo pinfo = type.GetProperty(name); // Get the property information for the specified property name
        object ret = pinfo?.GetValue(obj); // If pinfo != null, get the value of the property on obj
        return ret == null ? default(T) : (T)ret; // If ret is null, return the default value for T (for example, "" if T is string). If it isn't, return ret casted to T
    }

使用示例:

Form1.Text == Form1.GetProperty<string>("Text"); // true