2010-04-09 24 views
0

这可能听起来很疯狂,但我需要一个Nullable<T>(其中T是一个结构体)为其Value属性返回一个不同的类型。是否有可能重写可空结构的值,以返回一个不同的类型?

规则如果Nullable<T>的属性HasValue为true,则值将始终返回不同指定类型的对象(然后自身)。

我可能在思考这一点,但波纹管样的这个单元测试显示了我想做的事情。

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 
      } 
    } 
+2

它绝对显示你想要做什么,但是...为什么?那么你的鲍勃如何知道乔要回归什么? – 2010-04-09 20:53:29

+0

我会在重载属性中写入逻辑,或者不是。 – Andrew 2010-04-12 14:29:15

回答

3

你找一个user-defined implicit conversion如果是这样,你可以在鲍勃定义一个:

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 
+0

不错的一个!你不想要一个“隐式”吗? – Kobi 2010-04-09 20:56:38

+0

@Kobi:哈哈。我需要削减咖啡。是的,谢谢 - 我修正了我的例子。 – LBushkin 2010-04-09 20:57:39

+0

如果我没有记错,转换运算符不需要在类中定义。 – 2010-04-09 21:00:29

相关问题