简体   繁体   中英

How to make method to return generic type?

I have a class named config with one string field named key .

When I apply the GET property of the class, the property has to return one variable key in different types (Int or bool or String).

I implemented it as follow:

  public enum RetType {RetInt, RetBool, RetString};
  ...
  public object PolimorphProperty(string key, RetType how) 
  {
      get 
     { 
        switch (how)
        {
         case RetType.RetInt:
           ...;
        case RetType.RetBool:
           ...;
        case RetType.RetString:
           ...;
        }
     }  
 }

But the problem that PolimorphProperty returns Object type.

What should I change in the code to get the appropriate type (int,bool,string), not the object?

Do this:

public T PolimorphProperty<T>(string key)
{
    return (T) objectInstanceHere;
}

Usage example:

int i = PolimorphProperty<int>("somekey");

And this supports the http://www.antiifcampaign.com/

As much as possible avoid switch , if for that matter, in a polymorphic code.

public T PolimorphProperty<T>(string key, T how)
{
    //todo
}

Any type in C# is actually an object.
From what I understood from your question, you call your method this way:
PolimorpthProperty(key, RetType.SomeType)
The method returns an object. You should use it this way:
int key = (int)PolimorthProperty(key, RetType.RetInt);
This is called Unboxing .

How about this, consider that you original implementation of 'PolimorphProperty' remains im your project and you add this:

public TType PolimorphProperty<TType>(string key, RetType how) 
 {
     return (TType)PolimorphProperty(key, how);
 }

If I understood correctly, you are looking for something like this:

public T GenericMethod<T>(string key)
{
    var ret = new object(); // Retrieve object from whatever...
    return (T) ret;
}

public void UsageExample()
{
    int typedResult = GenericMethod<int>("myKey");
}

If you are trying to fetch different objects based on the type T, with different logic, than you'll have to switch on types anyway, Because unless your collection supports objects of certain type (they usually do), the compiler doesn't know what to do.
In this case, check this question .

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