For example, in Java, if I have a parameterized class, is it possible to do the following?
public class MyClass<T>{
public void aMethod {
..
T object = new T();
..
}
..
}
In Java, I think it is not possible, because the compiler doesn't know what constructor to call. But in C#? I don't know the language and I've read that many dark things can 开发者_如何学运维be done, so I was just wondering..
this is possible in C# if you are setting constraint on T type to have parameterless constructor.
public class MyClass<T> where T:new(){
public void aMethod {
..
T object = new T();
..
}
..
}
See here.
Like Donut said, C# allows you to instantiate arbitrary types at runtime using Activator.CreateInstance
which works a bit like Class<?>.newInstance
in Java. Since C#’s Generics are preserved after compilation, C#, unlike Java, allows you to get hold of a Type
instance for a given type parameter and thus call CreateInstance
or any other constructor.
For the parameterless constructor, this is considerably easier, using a generic constraint:
void <T> T createT() where T : new()
{
return new T();
}
The key here is where T : new()
.
In the general case, using reflection, you can use the following:
void <T> T createT()
{
var typeOfT = typeof(T);
return (T) Activator.CreateInstance(typeOfT, new object[] { arg1, arg2 … });
}
Yes, it's possible. You can use Activator.CreateInstance<T>();
From MSDN:
Activator.CreateInstance(T) Method
Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor.
In c# you can use the where keyword
private class MyClass<T> where T : new()
{
private void AMethod()
{
T myVariable = new T();
}
}
You can do this in Java via reflection:
public class Example {
public static void main(String[] args) throws Exception {
String s = create(String.class);
}
// Method that creates a new T
public static <T> T create(Class<T> c) throws InstantiationException, IllegalAccessException {
return c.newInstance();
}
}
One of the workarounds in Java that's less ugly: Javassist.
To summarize, in java there is no way to instantiate a generic type T. In C#, there are several ways.
Am I understanding this correctly?
精彩评论