我是C#的新手,假设我有4门课:
持票人:
public class Holder
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}SecondClass:
public class SecondClass
{
public void SecondClassMethod()
{
Holder holder = new Holder();
holder.Name = "John";
Console.WriteLine(holder.Name + " from SecondClass");
}
}AnotherClass:
public class AnotherClass
{
public void AnotherClassMethod()
{
Holder holder = new Holder();
holder.Name = "Raphael";
Console.WriteLine(holder.Name + " from AnotherClass");
}
}和期末课程:
class Program
{
static void Main(string[] args)
{
Holder x1 = new Holder();
SecondClass x2 = new SecondClass();
AnotherClass x3 = new AnotherClass();
x1.Name = "Nobody";
Console.WriteLine(x1.Name);
x2.SecondClassMethod();
Console.WriteLine(x1.Name);
x3.AnotherClassMethod();
Console.WriteLine(x1.Name);
Console.ReadLine();
}
}运行程序后输出:
Nobody
John from SecondClass
Nobody
Raphael from AnotherClass
Nobody我的问题是:如何使用Program类获得正确的名称(由其他类指定)?问题是我想用那套,上霍尔德的课。我搞不懂。
我想要:
Nobody
John from SecondClass
John
Raphael from AnotherClass
Raphaelas输出
发布于 2015-03-11 20:37:26
在每个类中实例化一个新实例 of Holder。为了修改现有实例,需要对其他类进行传递引用。
您可以通过引入构造函数实现这一点,您可以将对Holder实例的引用存储在私有 (最好是只读) 字段中。
public class SecondClass
{
private readonly Holder _holder;
public SecondClass(Holder holder)
{
_holder = holder;
}
public void SecondClassMethod()
{
_holder.Name = "John";
Console.WriteLine(_holder.Name + " from SecondClass");
}
}然后使用该类更改代码:
Holder x1 = new Holder();
SecondClass x2 = new SecondClass(x1);发布于 2015-03-11 20:55:44
此外,还可以在类中使用公共财产存储要修改的Holder实例的引用:
public class SecondClass
{
public Holder Holder { get; set; }
public SecondClass(){}
public void SecondClassMethod()
{
if (Holder!=null)
{
Holder.Name = "John";
Console.WriteLine(Holder.Name + " from SecondClass");
}
}
}然后在Main方法中可以这样做:
Holder x1 = new Holder();
SecondClass x2 = new SecondClass(){Holder=x1};
x2.SecondClassMethod();https://stackoverflow.com/questions/28996810
复制相似问题