开发者

C# Defining the Length of a Generic created using Reflection

I have code like this:

Type typPrecise = MostPrecise(typeof(int), typeof(double));//Evaluates to double

var varGeneric = typeof(Number<>);
var varSpecific = varGeneric.MakeGenericType(typPrecise);
dynamic nmNumber = Activator.CreateInstance(varSpecific);

The nmNumber is of dynamic type and essentially p开发者_运维问答roduces a Generic Number. How do I then specify the number of items in Number.

I basically want to accomplish this but by using the dynamic code above:

Number<typPrecise> whatever = new Number<typPrecise>(10);

An answer using 4.0 concepts is welcome.


Call the overload of Activator.CreateInstance that accepts constructor arguments:

dynamic nmNumber = Activator.CreateInstance(varSpecific, new object[] { 10 });

Incidentally note that the List<T>(int) constructor sets the initial capacity of the List, not the initial number of items (Count). The initial Count is always 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜