开发者

C#: Simplifying many similar implicit operator methods

I have a class with a bunch of implicit operators. In the code below, only a few examples of the implicit operators are used. I'm looking for any ideas how to refactor this, without making the SafeValue class generic. Any ideas?

public class SafeValue {
    private readonly object value;
    public SafeValue(object value) {
        if (value == somethingSpecial) {
            value = null;
        }
        this.value = value;
    }
    public static implicit operator string(SafeValue instance) {
        return (string)instance.value;
    }
    public static implicit operator int(SafeValue instance) {
 开发者_JAVA百科       if (instance.value == null) {
            throw new InvalidCastException("Cannot convert type");
        }
        return (int)instance.value;
    }
    public static implicit operator int?(SafeValue instance) {
        if (instance.value == null) {
            return null;
        }
        return new int?((int)instance.value);
    }
    public static implicit operator DateTime(SafeValue instance)
        if (instance.value == null) {
            throw new InvalidCastException("Cannot convert type");
        }
        return (DateTime)instance.value;
    }
    public static implicit operator DateTime?(SafeValue instance) {
        if (instance.value == null) {
            return null;
        }
        return new DateTime?((DateTime)instance.value);
    }
}


As i said in the comments, i think it would be best to replace the code completely.

If that is not an option, you might consider the following, mostly cosmetic changes:

  • You might want to get rid of the manually thrown exceptions. Why check for null and throw an exception if you would do so anyway in the next line? You are throwing exceptions in there anyway. Casting null to int will result in an exception.

  • Why all the new s ? No need for them. Just cast.

  • No need to doublecast your Nullables.

    DateTime? dt = (DateTime?) DateTime.Now; 
    

Works as expected

    DateTime? dt = (DateTime?) null; 

Also works (that is what you are doing anyway, since you return null; in your function that has a return value of DateTime? in the signature, right?

All your functions get reduced to only one line of code. Here is the DateTime? one in all its glory:

public static implicit operator DateTime?(SafeValue instance) {    
    return (DateTime?)instance.value;    
}

Repeat for int? and the like.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜