开发者

C# Wrapping a primitive

I known that deriving a class from a primitive is not possible, however, I would like my class to 'seem' like it's a primitive without casting. In this case, my class would operate much like a Decimal:

    public interface IFoo
    {
        static explicit operator Decimal(IFoo tFoo);
    }

    public class Foo: IFoo
    {
        private Decimal m_iFooVal;

        public Decimal Value
        {
            get { return m_iFooVal; }
            set { m_iFooVal= value; }
        }

        static explicit operator Decimal(IFoo tFoo)
        {
            return (tFoo as Foo).Value;
        }

    }

The above code doesn't work because the explicit operator cannot be defined in an interface. My code deals with interfaces and I开发者_如何学JAVA would like to keep it like that. Is it possible to convert IFoo to a Decimal? Any alternatives are welcome. Example:

IFoo tMyFooInterfaceReference = GetFooSomehow();    
Decimal iVal = tMyFooInterfaceReference;


Why not just add another method to your IFoo interface called ToDecimal() and call that when needed?

public interface IFoo
{
    decimal ToDecimal();
}

public class Foo : IFoo
{
    public decimal Value { get; set; }

    public decimal ToDecimal() { return Value; }
}

Your code wouldn't be that much more complicated:

IFoo tMyFooInterfaceReference = GetFooSomehow();
decimal iVal = tMyFooInterfaceReference.ToDecimal();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜