简体   繁体   中英

Change Type of Object to its SubType and Return it

I have a method that returns an Object of some type. On the receiving end, I want this object to be cast as the type it is without casting it. I can do this:

public static Object Method1(){
return GetObjectOfSomeType();
}

public static void Method2(){
MethodThatTakesBool((bool) Method1());
}

But I have a lot of methods similar to Method2 , and I wanted to avoid having to cast it every time. (It is not always a bool ...it is a different type every time.) What I would like to do is this:

public static Object Method1(){
return (GetType()) GetObjectOfSomeType();
}

public static void Method2(){
MethodThatTakesBool(Method1());
}

How can I cast an object as itself, then have that object returned as that type? I tried this, but it does not work:

return (myObject.GetType().ToString()) myObject;

The first thing to note is that it does not make sense to cast an object unless you know the desired type of the cast at compile time (ie "the static type").

However, you could make a generic method that hides the cast. It is entirely equivalent to having the cast in the calling code, but it looks like a method call, not a cast:

static T Method1<T>() {
    object res =  GetObjectOfSomeType();
    return (T)res;
}

Here is how to use this method:

public static void Method2(){
    MethodThatTakesBool(Method1<bool>());
    MethodThatTakesInt(Method1<int>());
}

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