【问题标题】:How to identify the <T> type for Int,String,Generic Type or class [closed]如何识别 Int、String、Generic 类型或类的 <T> 类型 [关闭]
【发布时间】:2018-11-22 15:01:12
【问题描述】:

这是我的代码, 我正在尝试但失败了。 T 采用任何类型的 DataType、Class 或 Generic 类。基于类型在类型中赋值。

   public T ToObject<T>()
        {
            //T is : int,int?,string,float,decimal 
            if (typeof(T).IsValueType)
            {
                //TO DO : Return Value Type
            }    
            //T is Generic List<User> 
            if (typeof(T).IsGenericType)
            {
                //TO DO : Return List of Object
            }
            else
            {
                //T is User 
                //TO DO : Return Object
            }                
            return default(T);
        }

【问题讨论】:

  • 你所说的“失败”是什么意思?我们需要更多细节。
  • 泛型代码的目的是generic。如果您正在检查类型并分支到特定于类型的代码,那么您可能根本不使用泛型。事实上,我觉得这个问题太模糊了,看不出你实际上想在这里实现什么
  • @Damien_The_Unbeliever 写了很多次代码,就像他写的一样。你不能简单地重载泛型的限制,也没有我想使用的所有限制。
  • 说实话,我不太明白这个方法的目的,你在那些分支中究竟会做什么?
  • @LasseVågsætherKarlsen 我有 DataTable 并且基于类型我想返回值,例如:1. 如果类型是 int、string、decimal 等然后从 Table.row[0][ 0], 2. 如果 Type 是类对象,则从第一行获取值, 3. 如果 Type 是 List,则返回 List

标签: c# string generics types int


【解决方案1】:

string 不是值类型,因此您的第一个条件会立即中断。

它真的不清楚你在问什么,至少可以说这似乎很奇怪。但是,在您的第一个示例中,IsValueType 不起作用,那么结构呢?您将如何区分?您可以使用属性IsPrimitive,但要小心,因为有些类型我们可以认为是原语,但它们不是,例如DecimalStringDateTimeTimeSpan 和还有很多。

if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) || ... )
{
    // Is Primitive, or Decimal, or String
}

然而,此代码仍不适用于可空类型,它们不会被标记为原始类型。

我真的认为你需要重新考虑你的设计,你将不得不做出如此多的例外,并且它会到处破坏。

泛型真的是你想要的吗?

FWIW,我认为您在其他地方遇到了设计或架构问题,导致您需要使用这样的通用方法,或者您对哪些类型是什么类型以及可以归类为哪些类型抱有不切实际的期望。

但是,如果您真的对此有心,您可以暂时将以下内容用于“原始类”类型

更新感谢 xanatos 的建议

private static readonly Type[] _types = {
      typeof(string),
      typeof(decimal),
      typeof(DateTime),
      typeof(DateTimeOffset),
      typeof(TimeSpan),
      typeof(Guid)
   };

public static bool IsSimpleType(Type type)
{
   Type baseType;
   return type.IsPrimitive || 
          type.IsEnum || 
          _types.Contains(type) || 
          ((baseType = Nullable.GetUnderlyingType(type)) != null && 
           IsSimpleType(baseType));
}

免责声明,我对您使用此代码致残和伤害的人不承担任何责任

【讨论】:

  • 为什么是Convert.GetTypeCode(type) != TypeCode.Object type != typeof(object)
  • @xanatos 确实不错,我回家后会进行一些测试并更新代码
  • 你甚至错过了检测枚举的代码...Enum 是一个没有真正直接使用的基本类型。
  • Convert.GetTypeCode(type) != TypeCode.Object 将返回true 任何不是object...我不认为这是他想要的...
  • 我建议删除typeof(Enum) 然后:Type baseType; return type.IsPrimitive || type.IsEnum || _types.Contains(type) || ((baseType = Nullable.GetUnderlyingType(type)) != null &amp;&amp; IsSimpleType(baseType));
【解决方案2】:
Type typeValue = typeof(T);

您可以参考typeof了解更多详情

【讨论】:

    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 2022-12-13
    • 2021-09-08
    • 2013-11-29
    • 1970-01-01
    相关资源
    最近更新 更多