简体   繁体   English

无法从'方法组'转换为'Func <string,string,bool>'

[英]Cannot convert from 'method group' to 'Func<string, string, bool>'

I am implementing a very simple rules engine that enforces some specifications dynamically at runtime. 我正在实现一个非常简单的规则引擎,它在运行时动态地强制执行某些规范。

The actual rules are stored in Tuples, and I have trouble storing a delegate to the string.EndsWith function. 实际规则存储在元组中,我将string.EndsWith存储到string.EndsWith函数时遇到问题。

The following code works for testing string equality, and returns False as expected ( "A" is different from "B" ): 以下代码用于测试字符串相等性,并按预期返回False"A""B"不同):

var rule = new Tuple<string, Func<string, string, bool>, string>("A", string.Equals, "B");
Console.WriteLine(rule.Item2.Invoke(rule.Item1, rule.Item3));

However, I cannot figure out how to adapt this code to use the string.EndsWith function instead of string.Equals . 但是,我无法弄清楚如何调整此代码以使用string.EndsWith函数而不是string.Equals

The following code does not compile and issues a Cannot convert from 'method group' to 'Func<string, string, bool>' error message in Visual Studio. 以下代码无法编译并在Visual Studio中发出Cannot convert from 'method group' to 'Func<string, string, bool>'错误消息。

var rule = new Tuple<string, Func<string, string, bool>, string>("A", string.EndsWith, "B");
Console.WriteLine(rule.Item2.Invoke(rule.Item1, rule.Item3));

I did search before asking this question, but I cannot understand the answers provided in How do I fix 'compiler error - cannot convert from method group to System.Delegate'? 我在问这个问题之前做过搜索,但是我无法理解我如何解决'编译错误 - 无法从方法组转换为System.Delegate'中提供的答案 or Cannot convert from method group to System.Func<string> . 无法从方法组转换为System.Func <string> I do not see how to apply these to my problem. 我不知道如何将这些应用于我的问题。

String.Equals and String.EndsWith have different method signatures and must be called differently. String.EqualsString.EndsWith具有不同的方法签名,必须以不同方式调用。

Specifically, String.Equals is static and takes two strings and returns a bool. 具体来说,String.Equals是静态的,需要两个字符串并返回一个bool。 String.EndsWith is an instance method taking one string and returns a bool String.EndsWith是一个实例方法,它接受一个字符串并返回一个bool

You can resolve your issue by wrapping the String.EndsWith call in a lambda to change the signature to take two strings and return a bool: 您可以通过在lambda中包装String.EndsWith调用来更改签名以获取两个字符串并返回bool来解决您的问题:

var rule = new Tuple<string, Func<string, string, bool>, string>
    ("AB", (string a, string b) => a.EndsWith(b), "B");
Console.WriteLine(rule.Item2.Invoke(rule.Item1, rule.Item3));

In general, the error means that there is no way the compiler can interpret string.EndsWith as a Func<string, string, bool> . 通常,错误意味着编译器无法将string.EndsWith解释为Func<string, string, bool> You may find this answer about what is a method group helpful to understanding the error message. 您可以找到有关什么是有助于理解错误消息的方法组的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM