return class from function in c#

2019-06-23 18:10发布

Can I return class object from function in c# as a return value instead return string or int or ..etc

标签: c# class
3条回答
闹够了就滚
2楼-- · 2019-06-23 18:16

I'm assuming that you want to return a instance of a class from the function, then the answer is yes. An instance of a class is nothing more than an object like basically everything else in .NET.

Example:

public class MeaningfulClassName
{  
    public int Val1;
    public string Val2;
    ....
}

public class Processor
{
    public MeaningfulClassName MyFunction(int something, string somethingelse)
    {
        var ret = new MeaningfulClassName();

        ....

        return ret;
    }
}
查看更多
Juvenile、少年°
3楼-- · 2019-06-23 18:21

I read your question as if a method can return a class. I would, presently, dare say No. Presently is 2018-04-05

Below I am using System.Class, a class most famous for System.Class.WriteLine.

One can not declare

Func<System.Class> C => System.Class;

to be able to

C.WriteLine("Hello world!");

Someone Please prove me Wrong!
I would really love the functionality as it would help med mock a static.

查看更多
混吃等死
4楼-- · 2019-06-23 18:24

A class object in C# is a Type. So you can definitely return it from a function:

public Type Foo() {
    return typeof(string);
}

public Type Bar() {
    return someNonNullVariable.GetType();
}
查看更多
登录 后发表回答