Re: Getting the Type of a Generic Parameter
- From: "Günter Prossliner" <g.prossliner/gmx/at>
- Date: Tue, 11 Dec 2007 16:12:55 +0100
Hello Rick!
The problem is that I don't actually need create a type from the
generic parameter, but need to instantiate the type specified BY the
parameter. The generic parameter is an object and I need to
instantiate that type. IOW, it's not - for example - List<T> that I
need to instantiate but T itself.
In essence what I need to do is:
Activator.CreateInstance<T>();
with the added requirement of passing constructor parameters.
You just have to use a typeof(T) in order to call the CTOR or to use
Activator:
class C<T> where T:Something{
void foo() {
Type t = typeof(T);
ConstructorInfo ctor = t.GetConstructor(
new Type[]{typeof(int), typeof(string)}
);
if(ctor == null)
throw new ArgumentException("T is invalid, because no CTOR(int,
string) is available!");
Something instance = (Something)ctor.Invoke(new object[]{1,
"hello"});
// do whatever you want
}
}
OK?
GP
.
- References:
- Getting the Type of a Generic Parameter
- From: Rick Strahl
- Re: Getting the Type of a Generic Parameter
- From: Günter Prossliner
- Re: Getting the Type of a Generic Parameter
- From: Rick Strahl
- Getting the Type of a Generic Parameter
- Prev by Date: Re: Windows service crash
- Next by Date: Thread-safety guarantees for basic ops
- Previous by thread: Re: Getting the Type of a Generic Parameter
- Next by thread: Re: Getting the Type of a Generic Parameter
- Index(es):
Relevant Pages
|
Loading