将属性打包到类型对象中并将其作为方法返回

时间:2017-12-05 06:33:09

标签: c#

我想在方法中创建类型对象的实例,添加到它的两个属性并返回对象作为方法的结果。

public object method()
{
TypeOfClassA a;
int b;
if(method(out a, out b))
{
res = new {a=a, b=b};
}
return res;
}

像这样的东西

2 个答案:

答案 0 :(得分:0)

你的问题是退货声明。如果您未输入(admin-venv)[ec2-user@ip-***-**-**-*** encoding]$ ls -l -rw-r--r-- 1 root root 95621513 Dec 5 13:14 What Is A_ V Can???and Can't???It Offer Us_ (ABC) (720p_30fps_H264-192kbit_AAC).mp4 (admin-venv)[ec2-user@ip-***-**-**-*** encoding]$ python Python 2.7.12 (default, Sep 1 2016, 22:14:00) [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> media_path = "What Is A_ V Can???and Can't???It Offer Us_ (ABC) (720p_30fps_H264-192kbit_AAC).mp4" >>> import os >>> print os.path.isfile(media_path) False >>> quit() ,则变量if-body未声明

res

在已调整的代码段中,我们只返回public object method() { TypeOfClassA a; int b; if(method(out a, out b)) { res = new {a=a, b=b}; return res; } return null; } (如果已创建)。否则,我们会返回res

答案 1 :(得分:0)

如果您不想Tuple<T1, T2>,那么dynamic是您唯一的选择。

public dynamic method()
{
    TypeOfClassA a;
    int b;
    if(method(out a, out b))
    {
        var res = new {a=a, b=b};
        return res;
    }

    return null; // You need to return something here. What happens if the if statement is not executed?
}

您可以像这样致电method

dynamic val = method();
Console.WriteLine(val.a); // or "val.b"