为什么func<>在字段初始化器静态?

时间:2015-09-19 03:44:01

标签: c# wpf func idataerrorinfo

在实现IDataErrorInfo时,以下代码编译并正常运行:

public string Error
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get
            {
                switch (columnName)
                {
                    case "MemberId":            return validate(MemberId,           0, RegexLibrary.NonEmptyRegex);
                    case "PolicyType":          return validate(PolicyType,         1, RegexLibrary.NonEmptyRegex);
                    case "EffectiveDateFrom":   return validate(EffectiveDateFrom,  2, RegexLibrary.DateRegex);
                    case "EffectiveDateTo":     return validate(EffectiveDateTo,    3, RegexLibrary.DateRegex);
                    case "Phone":               return validate(Phone,              4, RegexLibrary.PhoneRegex);
                    case "CompanyName":         return validate(CompanyName,        5, RegexLibrary.NonEmptyRegex);
                }
                // string.Empty is no error.
                return string.Empty;
            }
        }

 public string validate(string column, int position, string regex)
        {
            string invalid = string.Format("{0} is invalid.", column);
            if (column == null)
            {
                SetErrorStatus(1, position);
                return invalid;
            }

            Match match = Regex.Match(column, regex);
            if (!match.Success)
            {
                SetErrorStatus(1, position);
                return invalid;
            }

            SetErrorStatus(0, position);
            return string.Empty;
        }

但是,如果将validate(...)定义为如下函数:

Func<string, int, string, string> validate = (column, position, regex) =>
        {
            string invalid = string.Format("{0} is invalid.", column);
            if (column == null)
            {
                SetErrorStatus(1, position);
                return invalid;
            }

            Match match = Regex.Match(column, regex);
            if (!match.Success)
            {
                SetErrorStatus(1, position);
                return invalid;
            }

            SetErrorStatus(0, position);
            return string.Empty;

        };

编译器将validate(...)func定义为static。为什么呢?

TIA

2 个答案:

答案 0 :(得分:1)

在这种情况下,validate不是方法,而是字段。该字段是实例成员。分配给该字段的对象是一个引用匿名方法的委托。该方法没有理由成为实例成员,因为它不会对当前实例进行任何引用。所以,你有一个实例字段引用静态方法。

答案 1 :(得分:1)

编译器在调用类而不是实例1上生成static方法的事实是编译器的实现细节,它可能会发生变化,实际上是。您可以看到Delegate caching behavior changes in Roslyn并且现在看到,即使对于非捕获委托,编译器也会生成一个显示类。

我不知道这与在你的班级中声明static之类的内容有什么关系。