相关疑难解决方法(0)

是否在C#中继承了隐含/显式转换方法?

我不确定我在这里做错了什么.我有一个泛型类,它基本上是一个美化的整数,有一些方法可以进行某些字符串格式化,以及进入/来自string和int转换:

public class Base
{
    protected int m_value;
    ...
    // From int
    public static implicit operator Base(int Value)
    {
        return new Base(Value);
    }
    ...
    // To string
    public static explicit operator string(Base Value)
    {
        return String.Format("${0:X6}", (int)Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

它运作良好.我可以成功使用隐式和显式转换:

Base b = 1;
Console.WriteLine((string)b);  // Outputs "$000001", as expected.
Run Code Online (Sandbox Code Playgroud)

然后我从这个类派生出不同的子类,它们打开/关闭m_value中的不同命名位.例如:

public class Derived : Base
{

}
Run Code Online (Sandbox Code Playgroud)

然后我不能使用我的隐式转/ int转换:

Derived d = 3;
// Cannot implicitly convert type 'int' to 'Derived'. An explicit conversion exists (are you missing a …
Run Code Online (Sandbox Code Playgroud)

c# inheritance

7
推荐指数
1
解决办法
4836
查看次数

标签 统计

c# ×1

inheritance ×1