英文:
Equivalent of Tuple.Create for Actions and Funcs
问题
.NET 中关于 Tuple
的一个很酷的事情是,你可以这样创建它而不需要输入如下代码:
var x = new Tuple<string, string, int, float, int>("Hi", "Hello", 15, 5.5f, 500);
你可以这样输入:
var x = Tuple.Create("Hi", "Hello", 15, 5.5f, 500);
正确的泛型 Tuple
将会为你创建。
同样的快捷方式对于 Action
和 Func
也很有用。因为似乎对它们不可用,那么如何实现这样的功能,以便不需要输入如下代码:
var x = new Action<string, float, int>((s, f, i) => { /* 做些什么 */ });
或者更糟糕的情况下,这样输入:
var x = new Action<string, float, int>((string s, float f, int i) => { /* 做些什么 */ });
你可以像这样输入:
var x = Action.Create((string s, float f, int i) => { /* 做些什么 */ });
// x 变成了一个 Action<string, float, int>
尽管长度相同,但后一种示例更清晰地显示了参数是什么,总体看起来更整洁。
如何实现这样的扩展方法?请注意,我正在使用 .NET 6.0 和 C# 10.0。
英文:
A cool thing about Tuple
s in .NET is that instead of typing:
var x = new Tuple<string, string, int, float, int>("Hi", "Hello", 15, 5.5f, 500);
You can type
var x = Tuple.Create("Hi", "Hello", 15, 5.5f, 500);
And the correct generic Tuple
will be created for you.
The same shortcut would be beneficial for Action
s and Func
s. Since this doesn't seem to be available for them, how would one implement it, so that instead of typing this:
var x = new Action<string, float, int>((s, f, i) => { /* do something */ });
or even worse, this:
var x = new Action<string, float, int>((string s, float f, int i) => { /* do something */ });
you can type something nice like this:
var x = Action.Create((string s, float f, int i) => { /* do something */ });
// x becomes an Action<string, float, int>
Even though the length is the same, the latter example makes what the parameters are more clear, and it looks neater overall.
How can I implement such an extension method? Note that I'm using .NET 6.0 with C# 10.0
答案1
得分: 3
自C# 10起,引入了“自然函数类型”。你甚至不需要这样的方法 - 只需直接编写Lambda表达式并将其分配给一个var
,C#可以推断委托的类型。
var action = (string s, float f, int i) => { ... };
请注意,如果参数太多,这不一定是Action
。Action
类型是有限的,仅支持有限数量的参数。
如果你真的想要一个方法,可以这样做:
var anotherAction = Actions.Create((string s, float f, int i) => { ... });
public static class Actions {
public static T Create<T>(T t) where T : Delegate => t;
}
因为自然函数类型在调用方法时也适用。
英文:
Since C# 10, there are "natural function types". You don't even need such a method - just by writing the lambda directly and assign it to a var
, C# can infer the type of the delegate.
var action = (string s, float f, int i) => { ... };
Note that this is not necessarily Action
if you have too many parameters. There are only a finite number of Action
types, which supports up to a limited number of parameters.
If you really want a method, you can do:
var anotherAction = Actions.Create((string s, float f, int i) => { ... });
public static class Actions {
public static T Create<T>(T t) where T: Delegate => t;
}
because natural function types also work when you call a method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论