[英]Getting values from a multiple constructor
Here is the sample code: 这是示例代码:
class Class1
{
string a;
public Class1(string over) : base()
{
this.a = over;
Console.WriteLine(a);
}
public Class1(bool check)
{
if(check)
Console.WriteLine(a);
}
}
class Program
{
static void Main(string[] args)
{
Class1 myClass1 = new Class1("test");
Class1 myClass2 = new Class1(true);
Console.ReadLine();
}
}
What I want to happen is to get the value of string a from the 1nd Constructor Class1(string)
and display it to Constructor Class1(bool)
. 我想发生的是从第一个构造函数Class1(string)
获取字符串a的值,并将其显示给构造函数Class1(bool)
。 How can I do that? 我怎样才能做到这一点?
You have two different instances of Class1: myClass1 and MyClass2 If 'a' needs to be shared across instances, then you can make it static. 您有两个不同的Class1实例:myClass1和MyClass2如果需要在实例之间共享“ a”,则可以将其设为静态。
That way, setting 'a' in any instance of Class1 will apply to all instances. 这样,在Class1的任何实例中设置“ a”将适用于所有实例。
Make string a
static. 将string a
设为静态。 That way, all instances of Class1 reference the same string. 这样,Class1的所有实例都引用相同的字符串。
This should work, but i dont think you should be doing that. 这应该有效,但是我不认为您应该这样做。
class Class1 {
static string a;
public Class1(string over) : base() {
a = over;
Console.WriteLine(a);
}
public Class1(bool check) {
if(check)
Console.WriteLine(a);
}
}
class Program {
static void Main(string[] args) {
Class1 myClass1 = new Class1("test");
Class1 myClass2 = new Class1(true);
Console.ReadLine();
}
}
}
Pass myClass1 to myClass2 in a method call (or in the constructor) 在方法调用中(或在构造函数中)将myClass1传递给myClass2
It is hard to tell what to do because Class1, a, over, check. 很难说该怎么做,因为Class1结束了检查。 They don't make sense to me. 他们对我没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.