I have the following code:
public class ClassExample { void DoSomthing<T>(string name, T value) { SendToDatabase(name, value); } public class ParameterType { public readonly string Name; public readonly Type DisplayType; public readonly string Value; public ParameterType(string name, Type type, string value) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); if (type == null) throw new ArgumentNullException("type"); this.Name = name; this.DisplayType = type; this.Value = value; } } public void GetTypes() { List<ParameterType> l = report.GetParameterTypes(); foreach (ParameterType p in l) { DoSomthing<p.DisplayType>(p.Name, (p.DisplayType)p.Value); } } }
Now, I know I cannot perform DoSomething() is there any other way to use this function?
When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
A generic method may be overloaded like any other method. A class can provide two or more generic methods that specify the same method name but different method parameters.
You can, but it involves reflection, but you can do it.
typeof(ClassExample) .GetMethod("DoSomething") .MakeGenericMethod(p.DisplayType) .Invoke(this, new object[] { p.Name, p.Value });
This will look at the top of the containing class, get the method info, create a generic method with the appropriate type, then you can call Invoke on it.
this.GetType().GetMethod("DoSomething").MakeGenericMethod(p.Value.GetType()).Invoke(this, new object[]{p.Name, p.Value});
Should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With