I have a base class that needs to initialize a variable that will change depending on which child is calling the constructor. So,
public class TestClass<T> {
T variable;
string parameter;
public TestClass(passed_in_constructor) {
variable = passed_in_constructor(parameter);
}
}
How do I do this?
EDIT: Let me rephrase the question. Below is an alternate way of doing what I am trying to do and I can better explain the error and the problem
I currently have the following class:
public class Test<T> {
SqlConnection conn;
T genericGuy;
public Test() {
conn = ...this is initialized properly
genericGuy = (T)Activator.CreateInstance(typeof(T), sqlConn);
}
}
When I run this however, I am getting an Error. My 'T' is actually an interface and so the error says that there is no constructor defined in this interface.
I want the constructor under the interface to get called though...how can I do this?
Pass a Func
. Let the child decide what to do with that variable:
class Foo<T>
{
T variable;
string parameter;
public Foo(Func<string, T> action)
{
variable = action(parameter);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.