using System;
namespace ConsoleApp1
{
public class Panda
{
public Panda Mate;
public void Marry(Panda partner)
{
Mate = partner;
partner.Mate = this;
}
}
class Program
{
static void Main(string[] args)
{
Panda female= new Panda { };
Panda male= new Panda { };
male.Marry(female);
// female.Marry(male);
Console.WriteLine(male.Mate.ToString());
Console.WriteLine(female.Mate.ToString());
Console.ReadLine();
}
}
}
}
此代码来自Albahari并添加了我的代码。如何将相关合作伙伴名称输出到字符串?我想根据阶级关系输出男性伴侣姓名和男性伴侣姓名。我需要返回类实例名称而不是返回其属性的名称。或者name属性应该自动命名为类实例。
I try
var name = nameof(female.Mate);
Console.WriteLine(name);
Console.ReadLine();
} but this outputs "Mate"
答案 0 :(得分:2)
public class Panda
{
public string name;
public Panda Mate;
public void Marry(Panda partner)
{
Mate = partner;
partner.Mate = this;
}
public override string ToString()
{
return this.name + " = " + Mate.name;
}
}
class Program
{
static void Main(string[] args)
{
Panda female = new Panda { };
Panda male = new Panda { };
female.name = "Lilly";
male.name = "Shadow";
male.Marry(female);
// female.Marry(male);
Console.WriteLine(male.ToString());
Console.WriteLine(female.ToString());
Console.ReadLine();
}
}
已更新
请尝试此代码
public class Panda
{
public string name;
public Panda Mate;
public void Marry(Panda partner)
{
Mate = partner;
partner.Mate = this;
}
public override string ToString()
{
return this.name + " = " + Mate.name;
}
}
class Program
{
static void Main(string[] args)
{
Panda female = new Panda { };
Panda male = new Panda { };
female.name = nameof(female);
male.name = nameof(male);
male.Marry(female);
Console.WriteLine(male.ToString());
Console.WriteLine(female.ToString());
Console.ReadLine();
}
}