我有一个名为 Person 的类
public class Person
{
string name;
int age;
SampleObject(string name, int age)
{
this.name = name;
this.age = age;
}
public override string ToString()
{
string s = age.ToString();
return "Person: " + name + " " + s;
}
}
我已经覆盖了 ToString() 以返回人名。
我正在另一个类(class)中使用该类(class):
public class MyClass
{
public int Id {get;set;}
public Person person {get;set;}
}
现在,我想访问这个类
MyClass my = new MyClass();
我希望当我执行 my.person
时,它应该返回 person 类的 ToString() 值而不显式调用 my.person.ToString()
是否可能,如果可能,我该如何实现。
谢谢
最佳答案
您可以创建另一个只读属性
public string PersonName { get {return this.person.ToString();} }
或者添加对可能的 null 的检查
public string PersonName
{
get
{
return (this.person == null) ? String.Empty : this.person.ToString();
}
}
根据您对通过同一属性设置人员的 Name
的评论
我认为具有分离/特定属性的方法将更易于维护
public string PersonName
{
get
{
return (this.person == null) ? String.Empty : this.person.ToString();
}
set
{
if(this.person == null)
{
this.person = new Person(value, 0);
}
else
{
this.person.Name = value;
}
}
}
关于c# - 返回类实例的默认 ToString() c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30952064/