问题是这样的:我想要一个具有泛型类型的外参数的泛型函数。将泛型类型限制为 ref-type,当然没有问题。但我想要一个完全不受限制的泛型类型!没有 new() 或类/结构限制!
public class A
{ }
public class B<T> : A
{
public T t;
public B(T i)
{
this.t = t;
}
}
public static class S
{
public static bool Test<T>(ref A a, out T t)
{
C<T> c = a as C<T>;
if(c != null)
{
t = c.t;
return true;
}
else
return false;
}
}
class Run
{
static void Main(string[] args)
{
C<SomeType> c = new C<SomeType>(new SomeType(...));
SomeType thing;
S.Test<SomeType>(c,thing);
}
}
上面的代码说明了我想要做什么。我想设置 out 参数,但只能在与所描述的条件相似的情况下。在错误的情况下,Test(...)
我对 的值完全不感兴趣out t
。但上面当然不是工作代码。上面的问题是必须初始化一个out
参数。但也许初始化有时很昂贵(取决于 的类型),我不想初始化一个虚拟类实例只是为了让编译器停止抱怨。那么问题就变成了:你如何初始化一个未知类型(如果它是一个类,确保它被初始化为 null)?T
那么理论上你应该能够写出类似的东西
public static bool Test<T>(ref A a, out T t)
{
//...
else
{
if(typeof(T).IsValueType)
{
t = (T)0; //Can't cast from int to T error (Yeah, this is a little tricky...)
//OR:
t = new T(); //No-no, doesn't have the new()-restriction on T (But we know it's a value type... life sucks)
}
else
t = null; //Error: Can't set to null! T could be valueType! (No it CAN'T... again life sucks)
return false;
}
}
但可惜事情并非如此简单。第一个问题是当 T 是值类型时,我们应该能够创建它,但编译器不会让我们创建它。第二个问题类似:“它可能是一个值类型!” - 不,我只是确定不是。它应该工作,但它没有。很烦人。
行。所以我们开始发挥创意......毕竟,有一个很好的类叫做 Object,它与 C#'ish 的所有东西都有特殊的关系。
public static bool Test<T>(ref A a, out T t)
{
//...
else
{
if(typeof(T).IsValueType)
{
t = (T)(object)0; //Works ONLY if T is valuetype: int, otherwise you get a "must be less than infinity"-error.
}
else
{
t = (T)(object)null; //Null ref exception in the cast...
}
return false;
}
}
这至少可以编译。但这仍然是垃圾。运行时错误大量。value-type 的问题在于 object-type 记住它真正的类型以及尝试转换为其他东西时......奇怪的事情发生了(无穷大?真的吗??)好吧,这该死的井应该是可行的!所以让我们更有创意!
public static bool Test<T>(ref A a, out T t)
{
//...
else
{
if(typeof(T).IsValueType)
{
//... still rubbish here
}
else
{
object o = null;
t = (T)o; //Tricked you stupid compiler!
}
return false;
}
}
这是正确的!它看起来是一个愚蠢的微不足道的变化......但这会编译 - 对于非值类型,它会运行并给出我们想要的结果!如果 T 是一个引用类型,它会被初始化为 null。仍然是值类型的问题。有点不情愿的创造力将注意力转向了反思。在对反射的东西进行了一些随机挖掘之后,寻找值得尝试的东西(不!你无法获得值类型的构造函数,它返回 null)我偶然发现了 msdn 上的一个小注释:
“要创建没有实例构造函数的值类型的实例,请使用 CreateInstance 方法。”
输入CreateInstance<T>()
- http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspx。
“编译器使用 CreateInstance 泛型方法来实现由类型参数指定的类型的实例化。”
现在我们到了某个地方!当然它确实说
“一般来说,在应用程序代码中没有使用 CreateInstance,因为类型必须在编译时已知。如果类型在编译时已知,则可以使用正常的实例化语法(C# 中的 new 运算符,Visual Basic 中的 New , C++ 中的 gcnew)。”
但是,嘿——我们不是在做一般的事情,我们处于创造模式,编译器对我们很暴躁。完全有理由尝试一下。
public static bool Test<T>(ref A a, out T t)
{
//...
else
{
if(typeof(T).IsValueType)
{
t = Activator.CreateInstance<T>(); //Probably not your everyday code...
}
else
{
object o = null;
t = (T)o;
}
return false;
}
}
和砰!就是这样!它完全有效!下面是在 VS2010SP1 和 MonoDevelop(使用 Unity3.4)中测试和运行的一些代码
使用系统;
namespace GenericUnrestrictedOutParam
{
class Program
{
class TestClass
{
public int i;
}
struct TestStruct
{
int i;
TestClass thing;
};
public static void NullWorkaround<T>(out T anything)
{
if (typeof(T).IsValueType)
{
anything = Activator.CreateInstance<T>();
}
else
{
object o = null;
anything = (T)o;
}
}
static void Main(string[] args)
{
int i;
float f;
string s;
TestStruct ts;
TestClass c;
NullWorkaround<int>(out i);
NullWorkaround<float>(out f);
NullWorkaround<string>(out s);
NullWorkaround<TestStruct>(out ts);
NullWorkaround<TestClass>(out c);
} //Breakpoint here for value-checking
}
}
还有光荣的“输出”(来自 locals-panel @breakpoint):
args {string[0]} string[]
i 0 int
f 0.0 float
s null string
- ts {GenericUnrestrictedOutParam.Program.TestStruct} GenericUnrestrictedOutParam.Program.TestStruct
i 0 int
thing null GenericUnrestrictedOutParam.Program.TestClass
c null GenericUnrestrictedOutParam.Program.TestClass
即使是带有值和类类型的结构也处理得很好:值类型为 0,类实例为空。 任务完成!