使用Func<>作为财产?

时间:2016-06-27 14:23:02

标签: c# winforms delegates

我有这个类用于验证控件:

public class Validation
{
    public object Control { get; set; }
    public string Message { get; set; }
    public Func<Control, bool> Custom { get; set; }

    public Validation()
    {
        //How to set Custom??
    }

    private bool IsValid()
    {
        Control c = Control as Control;
        if (c != null)
        {
            return (!string.IsNullOrWhiteSpace(c.Text));
        }

        return true;
    }
}

该类只检查控件的Text属性是否包含文本。

现在我想扩展该类,以便使用此类的特定表单可以设置自己的自定义方法来验证特定控件。

问题:如何将Custom属性设置为方法(默认IsValid或调用表单中的自定义方法?)

2 个答案:

答案 0 :(得分:0)

您需要重写一点,因为IsValid没有Custom函数的有效签名。

这个怎么样?

public Validation(Func<Control, bool> isValid = null)
{
    //How to set Custom??
    Custom = isValid ?? this.IsValid;
}

private bool IsValid(Control c)
{
}

您可以通过构造函数传递isValid的自定义实现。如果为null,则它将使用您班级中的IsValid方法。

答案 1 :(得分:0)

对我来说,似乎你的问题有点困惑。据我了解,您的IsValid()方法想要调用Custom函数(如果有)。

所以我想在调用Form你想做类似的事情:

Validation myCustomValidation = new Validation { Control = myTextBox };
Custom = ctl => ctl.Text == "validText";

您对Validation.IsValid()的实施可能如下:

private bool IsValid()
{    
    Control c = Control as Control;
    if (c == null) return true;

    if (Custom != null) return Custom(c);

    return (!string.IsNullOrWhiteSpace(c.Text));
}    

因此,在调用Form中,您可以提供lambda或方法进行自定义验证。并且您的IsValid()可以决定调用它(如果已设置)或使用其默认实现。

相关问题