【问题标题】:Is it possible to override Value on a nullable struct, to return a diffrent type?是否可以在可为空的结构上覆盖 Value 以返回不同的类型?
【发布时间】:2010-04-09 20:47:29
【问题描述】:

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

规则是如果Nullable<T> 的属性HasValue 为真,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
            }
    }

【问题讨论】:

  • 它肯定显示了你想做什么,但是......为什么?你的 Bob 怎么知道 Joe 返回什么?
  • 我会在重载属性中写逻辑,或者不写。

标签: c# struct nullable


【解决方案1】:

你在寻找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

【讨论】:

  • 不错的一个!你不想要implicit 吗?
  • @Kobi:哈哈。我需要少喝咖啡。是的,谢谢 - 我修正了我的例子。
  • 如果我没记错的话,转换运算符不需要在类中定义。
  • @Zach Johnson:我不这样。看看这个:msdn.microsoft.com/en-us/library/2x7fay24(VS.80).aspx
  • @LBushkin:哎呀!是的,你是对的。我确实以为我记得有一次做过,但我想不是……
猜你喜欢
  • 2019-08-29
  • 2017-01-18
  • 2018-09-10
  • 2018-03-18
  • 2012-07-01
  • 2013-10-26
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
相关资源
最近更新 更多