How do you declare a Func with an anonymous return type?

不羁岁月 提交于 2019-12-03 01:16:27

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...

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