代码之家  ›  专栏  ›  技术社区  ›  Andrew

是否可以重写可为null的结构上的值,以返回不同的类型?

  •  0
  • Andrew  · 技术社区  · 16 年前

    你可能觉得这很疯狂,但我需要一个 Nullable<T> (其中T是结构)为其值属性返回不同的类型。

    规则是如果 的属性HasValue为true时,Value将始终返回不同指定类型的对象(然后返回其本身)。

    我可能想得太多了,但下面的单元测试显示了我想做什么。

        public struct Bob
        {
                ...
        }
    
    
        [TestClass]
        public class BobTest
        {
                [TestMethod]
                public void Test_Nullable_Bob_Returns_Joe()
                {
                        Joe joe = null;
                        Bob? bob;
                        var bobHasValue = bob.HasValue; // returns if Bob is null
    
                        if(bobHasValue)
                                joe = bob.Value; //Bob returns a Joe
                }
        }
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   LBushkin    16 年前

    user-defined implicit conversion ? 如果是这样,您可以在Bob上定义一个:

    class Bob {
        static public implicit operator Joe(Bob theBob) {
           // return whatever here...
        }
    }
    

    如果你不能这样做是因为你没有权利改变 Bob , 你总是可以考虑写一个扩展方法:

    public static class BobExt {
        public static Joe ToJoe( this Bob theBob ) {
            return whatever; // your logic here...
        }
    }
    
    if(bobHasValue) 
        joe = bob.Value.ToJoe(); // Bob converted to a Joe