This might sound crazy to you, but I need a Nullable<T>
(where T is a struct) to return a different type for it's Value property.
Rules being if Nullable<T>
's Property HasValue is true, Value will always return an object of a different specified type (then itself).
I might be over thinking this, but this unit test bellow kind of shows what I want to do.
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 Jo开发者_StackOverflow中文版e
}
}
Are you look for a user-defined implicit conversion? If so, you can define one on Bob:
class Bob {
static public implicit operator Joe(Bob theBob) {
// return whatever here...
}
}
If you can't do this because you don't have access to change Bob
, you could always consider writing an extension method:
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
精彩评论