我可以从C#中的同一类方法调用构造函数吗?
我可以从我可以从C#中的同一类方法调用构造函数吗?,c#,.net,constructor,C#,.net,Constructor,我可以从C中的同一类方法调用构造函数吗 例如: class A { public A() { /* Do Something here */ } public void methodA() { /* Need to call Constructor here */ } } 简而言之,答案是否定的 除了以下特殊情况外,不能将构造函数作为简单方法调用: 创建一个新对象:var x=new ObjType() 从同一
C
中的同一类方法调用构造函数吗
例如:
class A
{
public A()
{
/* Do Something here */
}
public void methodA()
{
/* Need to call Constructor here */
}
}
简而言之,答案是否定的
除了以下特殊情况外,不能将构造函数作为简单方法调用:
创建一个新对象:var x=new ObjType()
从同一类型的另一个构造函数调用构造函数:
class ObjType
{
private string _message;
// look at _this_ being called before the constructor body definition
public ObjType() :this("hello")
{}
private ObjType(string message)
{
_message = message;
}
}
从构造函数调用基类型构造函数:
class BaseType
{
private string _message;
// NB: should not be private
protected BaseType(string message)
{
_message = message;
}
}
class ObjType : BaseType
{
// look at _base_ being called before the constructor body execution
public ObjType() :base("hello")
{}
}
UPD。关于在另一个答案中提出的初始化方法的解决方法-是的,这可能是一个好方法。但由于对象的一致性,这有点棘手,这也是构造函数存在的原因。任何对象方法都应在一致(工作)状态下接收对象(this
)。并且不能保证它从构造函数调用方法。因此,任何编辑该初始化方法或在将来调用构造函数的人(可能是您)都可以期望得到这种保证,这大大增加了出错的风险。当您处理继承时,这个问题会被放大。除了提供了回答这个问题的答案之外,解决问题的一个简单方法是定义一个初始化方法,该方法从构造函数和您的方法调用:
class A
{
private init()
{
// do initializations here
}
public A()
{
init();
}
public void methodA()
{
// reinitialize the object
init();
// other stuff may come here
}
}
简而言之,你不能调用构造函数,但你不必调用构造函数:)你能在methodA
中创建一个类a的新实例,然后使用这个新实例吗,临时实例?如果构造函数做了一些您需要在其他时间调用的事情,那么可能应该在它自己的方法中,您应该从methodA
调用该方法。实际上,我在构造函数中有连接字符串,它在某个阶段超时,为了避免超时错误,我需要调用方法中的构造函数您的代码结构有问题。为什么在构造器中有连接字符串?如果你想得到具体问题的帮助(而不是花时间猜测你想出的可能的解决方案),请创建一个