[英]Passing a Constructor into into base class constructor
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.
我的“ T”实际上是一个接口,因此错误表明该接口中没有定义构造函数。
I want the constructor under the interface to get called though...how can I do this? 我希望接口下的构造函数被调用...我该怎么做?
Pass a Func
. 通过
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.