有没有一种方法返回匿名类型的方法?方法、类型

2023-09-02 20:43:07 作者:Toshi

我知道我不能写这样的方法:

I know I can't write a method like:

public var MyMethod()
{
   return new{ Property1 = "test", Property2="test"};
}

我能做到这一点,否则:

I can do it otherwise:

public object MyMethod()
{
   return new{ Property1 = "test", Property2="test"}
}

但我不想做第二个选项,因为,如果我这样做,我将不得不使用反射。

but I don't want to do the second option because, if I do so, I will have to use reflection.

我为什么要这么做:

今天我在我的aspx页面的方法返回一个DataTable的结果,并我不能改变它,我想这个数据表转换为一个匿名方法,我想工作的性质用。我不想只创建一个类来做到这一点,我将需要执行相同的查询超过一次,我还以为要创建一个返回一个匿名类型将是一个很好IDEIA的方法。

Today i have a method inside my aspx page that returns a datatable as result and I cannot change it, I was trying to convert this DataTable to an Anonymous method with the properties that I want to work with. I didn't want to create a class only to do that and as I will need to perform the same query more than one time, I Thought to create a method that returns an anonymous type would be a good ideia.

推荐答案

返回它作为一个 System.Object的是仅的办法返回匿名类型的方法。不幸的是没有其他办法可以做到这一点,因为匿名类型进行了专门设计,prevent他们以这种方式使用。

Returning it as a System.Object is the only way to return an anonymous type from a method. Unfortunately there is no other way to do this since anonymous types were designed specifically to prevent their use in this way.

有一些技巧,你可以做结合返回一个对象,让你亲近。如果你有兴趣在此解决方法,请阅读无法从方法返回匿名类型?真的吗?。

There are some tricks that you can do to in conjunction with returning an Object that allow you to get close. If you are interested in this workaround please read Can't return anonymous type from method? Really?.

免责声明:的虽然我联系的文章确实表现出一个解决办法,这并不意味着它是一个好主意,做它。我想创建一个固定式时,使用这种方法会更安全,更容易理解极力劝阻你。

Disclaimer: Even though the article I linked does show a workaround that doesn't mean it is a good idea to do it. I would strongly discourage you using this approach when creating a regular type would be safer and easier to understand.