开发者

C# Generics: How can I use them generically?

[TestMethod]
public void TestMyGenericBaseClasses()
{ 
    Type typeCrazy = ThisPartyIsTypeCrazyWOOT();

    // How do I create a generic object?
    MadnessOhYeah<typeCrazy> sanity = new MadnessOhYeah<typeCrazy>();

    // How do I use a gener开发者_如何学运维ic object after it has been created?
    Assert.IsTrue(sanity.MyTrueFunction(), "this is sparta");

    // How do I call a generic function generically?
    bool result = MyFunction<typeCrazy>();

    Assert.IsTrue(result, "I did not get my teeth whitened!");

}

Is there any way to make this compile? (ThisPartyIsTypeCrazyWOOT returns a Type) Because this is a test, we're not concerned about having to use reflection or anything, unless that's just absolutely crazy.

I'm getting the vibe that this isn't going to be possible though, and that our test functions will just have to be more specific.


You need Type.MakeGenericType Method. Then Activator.CreateInstance Method.


Update 2: The first example I posted still doesn't 100% answer the question, since it involves a cast to List<int>, which is a type that is known at compile time. Below is a reflection-only solution that illustrates how you can use a generic type knowing nothing about the type argument itself. But, as you can see, it's... well, disgusting ;)

Type userType = GetUserSuppliedType();

// Now let's say userType is T.
// Then here we are getting the type typeof(List<T>).
// But, of course, there's no way to have any such information in the code.
Type listOfUserType = typeof(List<>).MakeGenericType(new[] { userType });

// This is effectively calling new List<T>();
object listObject = Activator.CreateInstance(listOfUserType);

// Do you see how messy this is getting?
MethodInfo addMethod = listOfUserType.GetMethod("Add");

// We better hope this matches userType!
object input = GetUserSuppliedInput();

// I suppose we could check it, to be sure...
if (input == null || input.GetType() != userType)
{
    throw new InvalidOperationException("That isn't going to work!");
}

// Here we are finally calling List<T>.Add(input) -- just in the most ass-
// backwards way imaginable.
addMethod.Invoke(listObject, new[] { input });

Update: OK, if you insist on doing this, here's an example of how it's possible—but very cumbersome!

Type genericListType = typeof(List<>);
Type listOfInt32Type = genericListType.MakeGenericType(new[] { typeof(int) });

object listObject = Activator.CreateInstance(listOfInt32Type);

List<int> list = (List<int>)listObject;

list.Add(1);

Generics can't quite work like this because a Type object could be anything. Consider this code:

var list = new List<int>();
list.Add(1);

The type of list in the above code is known to be List<int>, which defines what operations are legal on list such as Add(1).

Now consider this instead:

Type t = GetTypeFromIndeterminateSourceSuchAsUserInput();
var list = new List<t>();
list.Add(?);

When t is a Type object rather than the name of a type (like int) which the compiler can parse, it's not really possible to instantiate a generic type using that type—or rather, it's possible (see Andrey's answer), but you can't really use the resulting object in any sort of generic way.

Now, you might think that something like this ought to work:

Type t = typeof(int);
var list = new List<t>();
list.Add(1);

...but just because the value of t is known (by you) at compile time doesn't change the way things work in general.

Anyway, yes it's possible using reflection; but if you go down that path, you're committing to a pretty reflection-heavy solution. What I'm getting at is that in general it isn't a particularly realistic thing to do.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜