【问题标题】:C# Ensure that custom cast uses the sub type of a super type when iterating over list of super typeC#确保自定义转换在迭代超类型列表时使用超类型的子类型
【发布时间】:2011-03-31 14:51:55
【问题描述】:

我有以下代码。我的意图是这个自定义对象可以使用语法转换为 Int32 类型

i = (int) obj;

其中“obj”是“子类”类型。

类型转换的操作符定义在抽象 SuperType 的每个 SubType 中,也定义在抽象 SuperType 中。由于抽象超类型中的运算符不能标记为虚拟,因此超类型的强制转换会故意引发异常。

如果我尝试在 foreach 循环中进行强制转换,其中循环遍历“SuperType”类型列表运营商

我希望它会使用子类型进行转换。

我可能正在努力解决这个问题,但现在我对我是否可以通过我认为是一个优雅的解决方案来实现这一点感兴趣。

任何建议表示赞赏!

// 循环...

foreach (PriceIndexAction objs in objList)
{
    int i = (int) action;
}

// 超类..

   public abstract class SuperClass
    { 

        protected SuperClass( DateTime p1, int p2, int p3, int p4 )
        {
           ....
        }

        public static implicit operator Int32(PriceIndexAction obj)
        {
            throw new InvalidCastException( "No cast to System.Int32 exists for the abstract class   PriceIndexAction.");
        }
    }

// 子类..

public class SubClass : SuperClass
{

      public SubClass(DateTime p1, int p2 )
                    : base( p1, p2, 1, 2 )
      {
         ....
      }


      public static implicit operator Int32(SubClass obj)
      {
          return 2;
      }
 }`enter code here`

【问题讨论】:

    标签: c# .net


    【解决方案1】:
    public abstract class SuperClass
    {
        public static implicit operator int(SuperClass obj)
        {
            return obj.ToInt32();
        }
    
        protected abstract int ToInt32();
    }
    

    然后在派生类中覆盖/实现ToInt32

    【讨论】:

      【解决方案2】:

      自定义转换运算符不能是virtual(因为它们是static);这是不可能的。

      相反,您应该创建一个普通的abstract 实例方法。 (例如,ToInt)。
      然后,您可以从强制转换运算符调用它。

      【讨论】:

        猜你喜欢
        • 2015-03-12
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-06
        相关资源
        最近更新 更多