如何声明具有匿名返回类型的 Func? [英] How do you declare a Func with an anonymous return type?
问题描述
我需要能够做到这一点:
I need to be able to do this:
var getHed = () =>
{
// do stuff
return new { Property1 = value, Property2 = value2, etc...};
};
var anonymousClass = getHed();
但我收到一个错误,表明我需要明确声明 getHed.
But I get an error which indicates I need to explicitly declare getHed.
如何声明 Func 使得 T 是我要返回的匿名类型?
How do I declare Func such that T is the anonymous type I am returning?
如果您对我为什么需要这样做感到好奇,那是因为我使用的是允许自定义代码的 3rd 方软件,但仅限于一种方法.这会变得非常难以管理.我有一个想法,我可以使用匿名方法来帮助保持程序代码的组织.在这种情况下,为了帮助它,我需要一个新类,除了匿名之外我无法定义它.
In case you are curious why I need to do this, it is because I am using 3rd party software that allows customization code, but only within a single method. This can become very difficult to manage. I had the idea that I could use anonymous methods to help keep the procedural code organized. In this case, for it to help, I need a new class, which I cannot define except anonymously.
推荐答案
由于匿名类型基本上总是如此,解决方案是使用泛型方法,以便您可以使用方法类型推断:
As is basically always the case with anonymous types, the solution is to use a generic method, so that you can use method type inference:
public static Func<TResult> DefineFunc<TResult>(Func<TResult> func)
{
return func;
}
你现在可以写:
var getHed = DefineFunc(() =>
{
// do stuff
return new { Property1 = value, Property2 = value2, etc...};
});
这篇关于如何声明具有匿名返回类型的 Func?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!