我有一个通用的方法
bool DoesEntityExist<T>(Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;
Run Code Online (Sandbox Code Playgroud)
如何以下列方式使用该方法:
Type t = entity.GetType();
DoesEntityExist<t>(entityGuid, transaction);
Run Code Online (Sandbox Code Playgroud)
我一直收到愚蠢的编译错误:
找不到类型或命名空间名称't'(您是否缺少using指令或程序集引用?)
DoesEntityExist<MyType>(entityGuid, transaction);
Run Code Online (Sandbox Code Playgroud)
完美的工作,但我不想使用if指令每次调用具有单独类型名称的方法.
typeof(string).IsPrimitive == false
typeof(int).IsPrimitive == true
typeof(MyClass).IsClass == true
typeof(string).IsClass == true
typeof(string).IsByRef == false
typeof(MyClass).IsByRef == true // correction: should be false (see comments below)
Run Code Online (Sandbox Code Playgroud)
我有一个实例化T的新实例的方法,如果它是一个"复杂"类,则从一组源数据值中填充其属性.
(a)如果T是简单类型(例如字符串或int或其他类似的东西),则执行从源数据到T的快速转换.
(b)如果T是一个类(但不是像字符串这样简单的东西),那么我将使用Activator.CreateInstance并进行一些反射来填充字段.
是否有一种快速而简单的方法来判断我是否应该使用方法(a)或方法(b)?此逻辑将在通用方法中使用,其中T作为类型参数.