什么是匿名类的返回类型 [英] What's the return type of an anonymous class

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

问题描述

我有以前有个字符串返回类型的类。现在,我觉得我需要的不是一个字符串返回更多。我在想返回类似如下:

I have a class that used to have a string return type. Now I find I need to return more than a string. I was thinking to return something like below:

public string Test()
{
  return ( new { ID = 5, Name= "Dave" } );
}



这甚至可能,如果是这样那么这将是返回类型?我知道这不是字符串。

Is this even possible and if so then what would be the return type? I know it's not string ..

推荐答案

这是返回的对象确实有一个类,但它是匿名的,所以你不能在代码中指定。你只需要它返回为对象引用:

The object that you return does have a class, but it's anonymous so you can't specify it in the code. You just have to return it as an object reference:

public object Test() {
  return new { ID = 5, Name= "Dave" };
}

请注意,该匿名类型是该方法的范围未知,所以反射是一家以访问其属性的唯一方法。

Note that the anonymous type is unknown outside the scope of the method, so reflection is the only way to access its properties.

如果您希望能够方便地使用返回的对象,就应该声明一个类:

If you want to be able to use the returned object conveniently, you should declare a class:

public class TestResult
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public TestResult Test() {
    return new TestResult() { ID = 5, Name= "Dave" };
}



另一种方法是使用现有的类,它是否适合你的目的。 A KeyValuePair <​​/ code>接近你用什么,但随后的性能当然会被命名为而不是 ID 名称

public KeyValuePair<int, string> Test() {
  return new KeyValuePair<int, string>(5, "Dave");
}

这篇关于什么是匿名类的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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