构造函数中的属性和函数

本文关键字:函数 属性 构造函数 | 更新日期: 2023-09-27 18:19:39

我想这样做:

[AttributeUsage(AttributeTargets.Property, 
                Inherited = false, 
                AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
    readonly string showName;
    readonly Type controlType;
    public Type ControlType
    {
        get { return controlType; }
    } 
    readonly Func<Control, object> selector;
    public Func<Control, object> Selector
    {
        get { return selector; }
    } 

    public MyAttribute(string showName, 
                       Type controlType, 
                       Func<Control, object> selector)
    {
        this.showName = showName;
        this.controlType = controlType;
        this.selector = selector;
    }
    public string ShowName
    {
        get { return showName; }
    }
}
class Foo
{
    // problem. Do you have an idea?
    [My("id number", 
     typeof(NumericUpDown), 
     Convert.ToInt32(control=>((NumericUpDown)control).Value))] 
    public int Id { get; set; }
}

我想做一个包含名称、控件类型和选择器的属性,以便从控件中获取属性的值。

我试着去做,但做不到。

构造函数中的属性和函数

否,不能在属性装饰中使用匿名方法或lambda表达式。

顺便说一句,如果可以的话,它将是(移动control声明):

control=>Convert.ToInt32(((NumericUpDown)control).Value)

但是。。。你不能。使用通过反射解析的方法的字符串名称,或者使用类似于具有虚拟方法重写的属性类的子类的名称。

不能在属性声明中使用lambda表达式。我也遇到了这个问题,我用一本带字符串的字典作为Lambda的关键字来解决这个问题。在属性中,我只声明了lambda的键。

Dictionary<string, Func<Control, object>> funcDict = new Dictionary<string, Func<Control, object>>();
funcDict.Add("return text", c => c.Text);

属性的使用方式如下:

[MyAttribute("show", typeof(TextBox), "return text")]