[英]Design pattern for allowing functions to accept generic types
I've got two classes: 我有两节课:
public abstract class Uniform<T>
public class UniformMatrix4 : Uniform<Matrix4>
(So far....there will be more that implement different types) (到目前为止......将会有更多实现不同类型的东西)
And now lets say I want to write a function that will accept any uniform object... but I can't do that because there is no class called Uniform
, only the generic Uniform<T>
. 现在让我说我想编写一个接受任何统一对象的函数......但我不能这样做,因为没有名为Uniform
类,只有通用的Uniform<T>
。 So what's the best approach to solving this problem? 那么解决这个问题的最佳方法是什么?
Uniform<T>
implement IUniform
使Uniform<T>
实现IUniform
Uniform<T>
extend Uniform
使Uniform<T>
延伸Uniform
Uniform<T>
directly? 使我接受Uniform的所有函数都是通用的,以便它们可以直接采用Uniform<T>
? Make your methods generic as well, and you're good. 让你的方法也通用,你也很好。
Note that you always have the choice of using all generic type arguments on the function if needed, like this: 请注意,如果需要,您始终可以选择在函数上使用所有泛型类型参数,如下所示:
public void MyMethod<TUniform, T>(TUniform uniform) where TUniform: Uniform<T> {...}
The compiler will usually infer the type arguments on his own whenever you have a parameter, so that the call in fact looks like a normal method invocation in the C# source code: 只要有参数,编译器通常就会自己推断出类型参数,这样调用实际上就像C#源代码中的普通方法调用一样:
UniformMatrix4 uniform;
MyMethod(uniform); // the types of the generic functions are inferred
Admittedly intimidated to post this answer, but think it may be correct: 无可否认地发布了这个答案,但认为这可能是正确的:
public static Uniform<dynamic> MyMethod(dynamic myObject) {
//do stuff
return uniform;
}
Here is a Dino Esposito blog on the topic: 这是关于这个主题的Dino Esposito博客:
http://msdn.microsoft.com/en-us/magazine/ff796227.aspx http://msdn.microsoft.com/en-us/magazine/ff796227.aspx
Cheers, 干杯,
Matt 马特
public void MyMethod<T>(Uniform<T> uniform) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.