[英]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();
But I get an error which indicates I need to explicitly declare getHed.但是我收到一个错误,表明我需要明确声明 getHed。
How do I declare Func such that T is the anonymous type I am returning?我如何声明 Func 使得 T 是我要返回的匿名类型?
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.如果您对我为什么需要这样做感到好奇,那是因为我使用的是允许自定义代码的 3rd 方软件,但仅限于一种方法。 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;
}
You can now write:你现在可以写:
var getHed = DefineFunc(() =>
{
// do stuff
return new { Property1 = value, Property2 = value2, etc...};
});
Use the following generic method to let the compiler infer the anonymous type for you:使用以下通用方法让编译器为您推断匿名类型:
public static Func<T> MakeFn<T>(Func<T> f)
{
return f;
}
Usage:用法:
var getHed = MakeFn(() => new { Property1 = ..., Property2 = ... });
var anonymousClass = getHed();
// you can now access Property1 and Property2
var test = anonymousClass.Property1;
In short, it can't be done.简而言之,这是做不到的。
You need an additional, generic, method to trick the compiler into inferring the T
for you to be the anonymous type, such as the other answers here provides.您需要一个额外的通用方法来诱使编译器将
T
推断为匿名类型,例如此处提供的其他答案。
However, since you've written that this is a special case where everything has to fit inside a single method, then no, it cannot be done.但是,由于您已经写过这是一种特殊情况,其中所有内容都必须适合单个方法,因此不,它无法完成。
The compiler does not allow this syntax:编译器不允许使用以下语法:
var x = () => ...
It needs this:它需要这个:
DelegateType x = () => ...
As such, you need to trick the compiler into working out the right type for DelegateType
, which likely is Func<(anonymous type here)>
, and this can only be done through type inference.因此,您需要欺骗编译器为
DelegateType
出正确的类型,这可能是Func<(anonymous type here)>
,而这只能通过类型推断来完成。
However, type inference and generic parameters requires the method to be generic, and thus the need for the additional method that has to be a generic method to help the compiler do this type inference.但是,类型推断和泛型参数要求方法是泛型的,因此需要额外的方法必须是泛型方法来帮助编译器进行这种类型推断。
Since you need to stay inside one method...由于您需要留在一种方法中......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.