Call constructor as a function in C#

被刻印的时光 ゝ 提交于 2019-12-19 05:44:56

问题


Is there a way in C# to reference a class constructor as a standard function? The reason is that Visual Studio complains about modifying functions with lambdas in them, and often its a simple select statement.

For example var ItemColors = selectedColors.Select (x => new SolidColorBrush(x));, where selectedColors is just an IEnumerable<System.Windows.Media.Color>.

Technically speaking, shouldn't the lambda be redundant? select takes a function accepting a type T and returning type U. The solid color brush takes (the correct) type T here and returns a U. Only I see no way to do this in C#. In F# it would be something like let ItemColors = map selectedColors (new SolidColorBrush).

TL;DR: I guess I'm looking for the valid form of var ItemColors = selectedColors.select (new SolidColorBrush) which doens't require a lamba. Is this possible in C# or does the language have no way to express this construct?


回答1:


No you cannot reference a C# constructor as a method group and pass it as a delegate parameter. The best way to do so is via the lambda syntax in your question.




回答2:


You could lay out a formal method:

private static SolidColorBrush Transform(Color color)
{
    return new SolidColorBrush(color);
}

Then you can use Select like this:

var ItemColors = selectedColors.Select(Transform);



回答3:


I'm not sure I understand you correctly. But are you talking about a factory?

This way you can pass a value to the factory and it will create an instance for you.

SolidColorBrush brush = ColorBrushFactory.BrushFrom(color);

Hope this helped.



来源:https://stackoverflow.com/questions/3601743/call-constructor-as-a-function-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!