如何声明具有匿名返回类型的Func? [英] How do you declare a Func with an anonymous return type?

查看:111
本文介绍了如何声明具有匿名返回类型的Func?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够做到这一点:

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?

如果您好奇为什么我需要这样做,那是因为我使用的是第三方软件,该软件只允许在一种方法中使用自定义代码.这可能变得非常难以管理.我的想法是我可以使用匿名方法来帮助保持程序代码的有条理.在这种情况下,为了提供帮助,我需要一个新类,除非匿名,否则无法定义.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆