C # Generics: How can I use them in general?

[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 generic 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 compiler? (ThisPartyIsTypeCrazyWOOT returns a type). Since this is a test, we do not care about using reflection or anything else, unless it is completely insane.

I get a vibration that this will not be possible, and that our test functions just have to be more specific.

+3
source share
2 answers

2. , , 100%, List<int>, , . , , , . , , ... , ;)

Type userType = GetUserSuppliedType();

// Now let say userType is T.
// Then here we are getting the type typeof(List<T>).
// But, of course, there 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 });

: , , , , !

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 , Type . :

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

list , , List<int>, , list, Add(1).

:

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

t Type, (, int), , , , , (. Andrey answer), - .

, - :

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

... , t () , .

, , , ; , , . , , , .

+2

Source: https://habr.com/ru/post/1781731/


All Articles