简体   繁体   中英

C# return (dynamic or anonymous?) object with return values from other methods as properties

I would like to return an object, which stores the return values from other class methods as properties on the return object. The problem is that I do not know which is the best way to do this in C#. Currently I am using a sort of JavaScript-ish approach. Because I do not know the return type, I use the dynamic keyword.

class Test {

    public static dynamic MyExportingMethod() {
        return new {
            myString = MyStringMethod(),
            myInt = MyIntMethod()
        };
    }

    public static string MyStringMethod() {
        return "Hello";
    }

    public static int MyIntMethod() {
        return 55;
    }

   }

And then being able to access them like so,

var myReturnObjWithProps = Test.MyExportingMethod();
myReturnObjWithProps.myString; // should be "Hello"

So my questions are, should I use the dynamic return type? Am I not just returning an anonymous object?

Make a class for the return type. You want something strongly typed, both for performance and for clarity.

class Foo
{
    string MyString { get; set}
    int MyInt { get; set}
}

class Test 
{

    public static Foo MyExportingMethod() 
    {
        return new Foo
        {
            MyString = MyStringMethod(),
            MyInt = MyIntMethod()
        };
    }

    public static string MyStringMethod() 
    {
        return "Hello";
    }

    public static int MyIntMethod() 
    {
        return 55;
    }
}

You should use dynamic sparingly. This way anyone can see what your method is returning. If you return dynamic the caller has no way of knowing what to look for in the dynamic without looking at the source for your method. That way the abstraction goes away and well-structured programming is all about abstraction.

should I use the dynamic return type?

Yes - a method that returns dynamic effectively returns an object , so you have to use dynamic in order to access it's properties at runtime without reflection.

Am I not just returning an anonymous object?

You are, but the declared type of the method is effectively object so its properties cannot be referenced at compile-time.

Bottom line - you should avoid returning anonymous types from methods if at all possible. Use a defined type, or keep the creation and usage of the anonymous type in one method so you can use var and let the compiler infer the type.

An alternative to creating a new class simply for a method return would be ValueTuple :

public static (string myString, int myInt) MyExportingMethod()
{
    return (MyStringMethod(), MyIntMethod());
}

var (myString, myInt) = Test.MyExportingMethod();
myString; // == "Hello"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM