【问题标题】:How can I access to the method in class that returns a Generic Type如何访问返回泛型类型的类中的方法
【发布时间】:2012-07-15 18:23:53
【问题描述】:

我有一个名为 config 的类,其中包含两个字符串字段,分别名为 key paramValue 和 parameterPath。

当我应用类的ChooseType方法时,该方法必须返回一个不同类型(Int或bool或String)的变量paramValue。

我实现如下:

  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");

              }
          }   
      }
  }

我的问题是如何访问 ConfigValue 类中的 PolimorphProperty 方法,以检索例如 paramValue Int 类型。

【问题讨论】:

标签: c# .net


【解决方案1】:

我认为以下代码最符合您的要求(我在写到这里之前已经对其进行了测试......)

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

你可以这样调用代码:

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

注意事项:

  • 您确实不需要传递参数列表中的任何内容来确定返回值的类型。
  • 确保将 try-catch 放在要检查适合您未来使用的类型的任何位置。

【讨论】:

    【解决方案2】:

    同时拥有TRetType 是多余的。应该是这样的:

    class ConfigValue
    {
        public string paramPath;
        private string paramValue;
    
        public T PolimorphProperty<T>()
        {
            return (T)Convert.ChangeType(paramValue, typeof(T));
        }
    }
    

    将其称为configValue.PolimorphProperty&lt;int&gt;()

    或者如果你需要手动实现类型转换,你可以这样做:

    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));
        }
    }
    

    【讨论】:

    • 您可能应该展示一个如何调用此方法的示例,因为这是实际问题。
    猜你喜欢
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2021-04-09
    • 2011-05-11
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多