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.
How do I declare Func such that T is the anonymous type I am returning?
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;
}
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 Porperty1 and Property2
var test = anonymousClass.Porperty1;
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.
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.
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...
来源:https://stackoverflow.com/questions/41151747/how-do-you-declare-a-func-with-an-anonymous-return-type