我有一个LiteralObject类,默认情况下它继承自System.Object。这就是这个类的样子:
public LiteralObject(Object value)
{
this.value = value;
}
private Object value;
public Object getValue() { return value; }
要获取LiteralObject对象的值:
LiteralObject x = new LiteralObject(23);
Console.WriteLine(x.getvalue());
我想要的是这个:
LiteralObject x = new LiteralObject(23);
Console.WriteLine(x);
有没有办法覆盖System.Object对象的返回?或者还有其他方法可以得到我想要的东西吗?顺便说一句,重写ToString()不是我正在寻找的解决方案。传递给构造函数的对象与其父/基类具有相同的类型
你可以使用隐式转换运算符来做到这一点。但是它不适用于object
,因为你无法对object
(或任何其他祖先类)执行隐式转换。为了解决这个问题,我们可以使用泛型:
class LiteralObject<T>
{
public LiteralObject(T initialValue)
{
this.value = initialValue;
}
private T value;
public T getValue()
{
return value;
}
static public implicit operator T(LiteralObject<T> source)
{
return source.getValue();
}
}
public class Program
{
public static void PrintInteger(int i)
{
Console.WriteLine("{0}", i);
}
public static void Main()
{
var o = new LiteralObject<int>(23);
PrintInteger(o);
}
}
输出:
23