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

时间:2016-02-16 07:04:40

标签: c# winforms user-controls class-library

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

标签和textBox的文本将受外部项目的限制。在我导入dll的项目中。

我试图让用户控件完全通用。比方说,我会将任何对象和对象的属性名称发送到dll。 dll将读取对象,获取对象属性,获取已发送参数的值,并在win表单中充当另一个就绪控件。

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

只需这样说,myController1将获得与PropertyName1的{​​{1}}相关联的值,并将值与文本框和标签绑定。

1 个答案:

答案 0 :(得分:0)

你想用反射来做这件事。 这是你使用扩展方法的方法,但如果你需要的话,你可以轻松地使它成为常规功能。我试着通过评论来解释它的作用。

    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