开发者

C# Ensure that custom cast uses the sub type of a super type when iterating over list of super type

I have the following code. My intention that this custom object can be cast to type Int32 using the syntax

i = (int) obj;

where 'obj' is of type 'SubClass'.

The operator for the cast is defined in each SubType of the abstract SuperType, and is also defined in the abstract SuperType. Since the operator in the abstract super type cannot be marked as virtual, a cast from the super type intentionally causes an exception to be thrown.

If I try to cast within a foreach loop, where the loop iterates over a list of type 'SuperType' C# attempts to cast using the operator on the SuperType (and throws the programmed exception), where I want it to cast using the operator

I was hoping that it would cast using the sub type.

I'm probably going about this the hard way, but am interested now as to whether I can achieve this in what I felt was an e开发者_运维技巧legant solution.

Any advice appreciated!

// Loop...

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

// SuperClass..

   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.");
        }
    }

// SubClass..

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`


public abstract class SuperClass
{
    public static implicit operator int(SuperClass obj)
    {
        return obj.ToInt32();
    }

    protected abstract int ToInt32();
}

And then override/implement ToInt32 in derived classes.


Custom cast operators cannot be virtual (since they're static); this is not possible.

Instead, you should make a normal abstract instance method. (eg, ToInt).
You can then call it from a cast operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜