通过Control对象读取自定义控件属性的值

时间:2018-12-19 00:20:21

标签: c# custom-controls

我有3个自定义控件,它们都具有一个名为“ MyCustomProperty”的属性,假设我需要使用

foreach (control c in this.controls)

我如何通过对象c到达MyCustomProperty?

谢谢

3 个答案:

答案 0 :(得分:2)

步骤1。为您的控件提供一个公开该属性的通用接口。

interface IPropertyHolder
{
    string MyCustomProperty { get; }
}

class MyCustomControl1 : TextBox, IPropertyHolder
{
    public string MyCustomProperty { get; set; }
}

class MyCustomControl2 : Form, IPropertyHolder
{
    public string MyCustomProperty { get; set; }
}

class MyCustomControl3 : Control, IPropertyHolder
{
    public string MyCustomProperty { get; set; }
}

第2步。要么投射它:

foreach (var c in this.controls)
{
    var custom = c as IPropertyHolder;
    if (custom != null)
    {
        var temp = c.MyCustomProperty;
    }
}

或仅包括具有以下接口的控件:

foreach (var c in this.controls.OfType<IPropertyHolder>())
{
    var temp = c.MyCustomProperty;
}

答案 1 :(得分:1)

您可以使用反射来标识具有属性的控件,然后使用dynamic来访问属性:

using System.Reflection;

if (c.GetType().GetProperty("MyCustomProperty") != null)
{
  string something = ((dynamic)c).MyCustomProperty; //Assuming your property is a string
}

答案 2 :(得分:0)

测试控件的类型正确,然后通过给它命名(此处为myC)来强制转换:

if (c is MyCustomControl myC)
{
  var something = myC.MyCustomProperty;
}

以下是等效的内容,但可能更容易理解:

if (c is MyCustomControl)
{
  var myC = (MyCustomControl)c;
  var something = myC.MyCustomProperty;
}