c# - 返回类实例的默认 ToString() c#

标签 c#

我有一个名为 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/

相关文章:

c# - LINQ - SelectMany OrderBy 外部值然后内部值

c# - C# 中 RectangleShape 的边框样式

c# - 将大量 SQL 结果返回到 C# 数组

c# - 如何将 List<> 作为字段存储在数据库中? - C#(SQL Server 精简版)

c# - 并行计算多个值。等待所有线程完成

C# 的最佳重载方法匹配...有一些无效参数

c# - 在同步框架中配置适配器

c# - 如何在选择表达式中重用子查询?

c# - Mono 编译器生成的 .exe 直接从 linux 命令行运行,为什么?

c# - 如何在某些情况下使用不同的基类构造函数?