简体   繁体   中英

How can I access to the method in class that returns a Generic Type

I have a class named config with two string fields named key paramValue and parameterPath.

When I apply the ChooseType method of the class, the method has to return one variable paramValue in different types (Int or bool or String).

I implemented it as follow:

  class ConfigValue
  {
      public string paramPath;
      private string paramValue;

      public enum RetType {RetInt, RetBool, RetString};

       public T PolimorphProperty<T>(RetType how) 
       {

          { 
            switch (how)
             {
             case RetType.RetInt:
               return (dynamic)int.Parse(paramValue);

             case RetType.RetBool:
               return (dynamic)Boolean.Parse(paramValue);

             case RetType.RetString:
               return (T)(object)paramValue;

             default:
               throw new ArgumentException("RetType not supported", "how");

              }
          }   
      }
  }

My question is how can i access to the PolimorphProperty method in ConfigValue class, to retrive for examlple paramValue Int type.

Having both T and RetType is redundant. It should be something like this:

class ConfigValue
{
    public string paramPath;
    private string paramValue;

    public T PolimorphProperty<T>()
    {
        return (T)Convert.ChangeType(paramValue, typeof(T));
    }
}

Call it like configValue.PolimorphProperty<int>() .

Or if you need to implement the type conversion manually, you can do something like this:

class ConfigValue
{
    public string paramPath;
    private string paramValue;

    public T PolimorphProperty<T>()
    {
        if (typeof(T) == typeof(MySpecialType))
            return (T)(object)new MySpecialType(paramValue);
        else
            return (T)Convert.ChangeType(paramValue, typeof(T));
    }
}

I think following code best matches what you want (i have tested it before writing here...)

public T PolimorphProperty<T>()
{
      object tt = Convert.ChangeType(paramValue, typeof(T));
      if (tt == null)
         return default(T);
      return (T) tt;
}

And you can call the code like this:

 int ret = cv.PolimorphProperty<int>();

Notes:

  • You really do not need to pass anything in the param list to determine the type of the returned value.
  • Make sure you put try-catch wherever you are checking the appropraite type for your future usage.

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