简体   繁体   中英

Return any type of object from a function

Is there any way of returning an object from a function. The tricky part is the object can be of any type. I want a function to handle returning objects from session. So the object i want to return could be a product one minute but then i might want to return a customer the next minute. Is it possible or will I have to do a function to return each type.

  1. Return object it's the highest class.
  2. Make the Method generic.
  3. Return dynamic (thanks to @AustinSalonen)

public T Foo<T>(T obj)
{
    var variable = GetTFromFooElse();
    return variable; 
}

public dynamic Foo()
{
    var variable = GetSomethingFromFooElse();
    return variable;
}

Yes, you can return Type object . Though, you'll need to cast the result in the caller to use anything remotely useful.

static object CarFactory (){
    return new Car();
}

static void Main(){

    Car car = (Car)CarFactory();

    /* do stuff with car */
    car.Crash();
}

Note It is a standard to use generics as it provides the desired level of abstraction with Type safety...

Depending on your use cade, instead of using object maybe you could use generics for that?

Have a class Session<T> with a method

T GetResult()

You could the make instances like this:

var x = new Session<Product>();
var y = new Session<Customer>();

This way you get some nice type safety.

In this kind of scenario, you're better off wrapping up your session class via some kind of Service/Api.

For example:

public static class SessionAccess
{
    public static Something SomethingSession
    {
        get
        {
            return Session["Something"] as Something;
        }

        set
        {
            Session["Something"] = value;
        }
    }
}

It's important to have a consistent session-access mechanism, as to avoid accidentally stepping-over the same session key, and to ensure it's always the same underlying datatype.

如果您的方法返回一个对象,则可以返回任何所需的对象。

您的方法可以返回一个对象 ,但调用时必须将其转换为所需的对象。

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