C# 如何识别<;T>;Int、String、泛型类型或类的类型
这是我的密码, 我正在尝试但失败了。T是任何类型的数据类型、类或泛型类。基于类型在类型中指定值C# 如何识别<;T>;Int、String、泛型类型或类的类型,c#,string,generics,types,int,C#,String,Generics,Types,Int,这是我的密码, 我正在尝试但失败了。T是任何类型的数据类型、类或泛型类。基于类型在类型中指定值 public T ToObject<T>() { //T is : int,int?,string,float,decimal if (typeof(T).IsValueType) { //TO DO : Return Value Type
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);
}
publictoobject()
{
//T是:int,int?,字符串,浮点,十进制
if(类型(T).IsValueType)
{
//要执行的操作:返回值类型
}
//T是通用列表
if(typeof(T).IsGenericType)
{
//要执行的操作:返回对象列表
}
其他的
{
//T是用户
//要执行的操作:返回对象
}
返回默认值(T);
}
有关更多详细信息,请参阅
字符串
不是值类型,因此第一个条件立即中断
你问什么真的不清楚,至少可以说这很奇怪。然而,在您的第一个示例中,IsValueType
无法工作,那么structs呢?您将如何区分?您可以使用属性IsPrimitive
,但要小心,因为有些类型我们可以认为是原语,但它们不是,例如Decimal
,String
,DateTime
,TimeSpan
,等等
if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) || ... )
{
// Is Primitive, or Decimal, or String
}
然而,这段代码仍然不适用于可为空的类型,它们不会被标记为原语
我真的认为你需要重新考虑你的设计,你将不得不做出如此多的例外,它将打破各地
泛型真的是你想要的吗
FWIW,我认为您在其他地方遇到了设计或架构问题,这导致您需要使用这样的通用方法,或者您对类型是什么以及可以分类为什么有不切实际的期望
但是,如果您真的非常关注这一点,您可以尝试对“类原始”类型使用如下内容
由于xanatos sugestions的更新
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));
}
免责声明,我对您使用此代码伤残的人不承担任何责任您所说的“失败”是什么意思?我们需要更多的细节。泛型代码的目的是泛型。如果您正在检查类型并分支到特定于类型的代码,那么您可能根本不使用泛型。事实上,我觉得这个问题太模糊了,看不出你到底想在这里实现什么。@Damien_这个不信者写了很多次的代码,就像他写的一样。你不能简单地在泛型的限制上超载,也没有我想要使用的所有限制。老实说,我真的不明白这个方法的目的,你会在这些分支中做什么?@LasseVågsætherKarlsen我有DataTable,并且基于类型我想要返回值,例如,g:1。若类型为int、string、decimal等,则从表[0][0]行2获取值。若类型是类对象,那个么从第一行3获取值。如果Type是List,则返回ListWhy
Convert.GetTypeCode(Type)!=TypeCode.Object
<代码>类型!=typeof(object)@xanatos是的,确实很好,我会加入一些测试,回家后更新代码。你甚至会丢失检测枚举的代码Enum
是一种基本类型,实际上并没有直接使用。而Convert.GetTypeCode(type)!=TypeCode.Object
对于任何不是Object
的对象都将返回true
。。。我认为这不是他想要的……我建议删除typeof(Enum)
,然后:typebasetype;返回类型.IsPrimitive | | | type.IsEnum | | | | U类型。包含(类型)| |((baseType=Nullable.GetUnderlineingType(类型))!=null和IsSimpleType(baseType))代码>
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));
}