如何重写ToString()方法以获取Object的数据Member



我有一个返回对象的方法。如果我返回一个对象,那么它将给出类的完全限定名称。但是我想返回对象的数据成员。

public GetDetails GetInfo()
{
    GetDetails detail = new GetDetails("john", 47);
    return detail;
}
public override string ToString()
{
    return this.Name + "|" + this.Age;
}

我重写ToString()方法以获取detail对象的数据成员。但它不起作用。我怎样才能做到这一点?

您所要求的不起作用,因为detail是一个私有变量,并且在GetInfo()方法的范围内。因此,无法从该方法外部访问它。

很难猜测这两种方法的上下文是什么;但是,我认为您应该在类中保留state,以允许在ToString()方法中呈现detail

这个例子可能不是一个完美的解决方案,但它会解决你的问题:

class MySpecialDetails
{
    // declare as private variable in scope of class
    // hence it can be accessed by all methods in this class
    private GetDetails _details; // don't name your type "Get..." ;-)
    public GetDetails GetInfo()
    {
        // save result into local variable
        return (_details = new GetDetails("john", 47));
    }
    public override string ToString()
    {
        // read local variable
        return _details != null ? _details.Name + "|" + _details.Age : base.ToString();
    }
}

您可以创建一个字符串扩展方法。

 public static string StringExtension(this GetDetails input)
 {
     return input.Name + "|" + input.Age;
 }

这个静态方法通常在一个静态类中。然后你会这样称呼它

public string GetInfo() 
{
    GetDetails detail = new GetDetails("john", 47);
    return detail.ToString();
}

最新更新