是否可以创建仅接受具有特定属性的类型的泛型类

Ami*_*man 8 c# generics winforms

我想创建一个类"指标",它将接受"控制"并设置其"图像"属性.

由于Control没有Image属性,我想实现一个模板类("Indicator"),它只接受具有此属性的类(Image).

可能吗?

Fab*_*jan 19

我们可以通过添加私有无参数构造函数和另一个我们将进行类型检查的公共ctor 改变创建此类实例的方式:

class Indicator<T> where T : Control
{
    private T _control;

    private Indicator() 
    {
    }

    public Indicator(T control)
    {
       if(control.GetType().GetProperties().All(p => p.Name != "Image" || p.PropertyType != typeof(Image)))
       { 
          throw new ArgumentException("This type of control is not supported");
       }
       this._control = control;
    }
}
Run Code Online (Sandbox Code Playgroud)