使用值覆盖对象类型

时间:2016-04-15 11:23:31

标签: c#

我有一个接收并返回字符串的库(我想创建无限数字,但我简化了解释)。

我的库有运算符重载和更多源代码,但是当我使用库时:

MyType foo = new MyType("10");
MyType bar = foo + foo;
Console.WriteLine("{0}", bar.GetType());
Console.WriteLine("{0}", bar);
Console.WriteLine("{0}", bar.Value); // Redundant: the property "Value" has the value as string

输出结果为:

MyNamespace.MyType
MyNamespace.MyType // The object "bar" returns the object type
10

好吧,但我想获得" 10" (bar.Value)仅使用对象名称" bar":

Console.WriteLine("{0}", bar);
// I want the next output: 10

我尝试使用库中的GetType()进行更改(我发现它不可能覆盖GetType()):

public new string GetType()
{
    return this.Value;
}

但这仅适用于" bar.GetType()"而不是" bar"。

我认为在C#中是不可能的。

1 个答案:

答案 0 :(得分:3)

这可以通过覆盖Object.ToString()

轻松完成
class MyType
{
    public string Value { get; set; }
    public override string ToString() { return this.Value; }
}

测试:

MyType m = new MyType("10");
Console.WriteLine(m);

打印10

Explenataion:调用WriteLine时调用类ToString - 方法。如果在类型中未覆盖此方法,则使用object的默认实现,这将简单地返回类的类型,在您的情况下为MyNamespace.MyType

相关问题