无法在C#中投的F#对象

问题描述:

鉴于此F#:无法在C#中投的F#对象

namespace DU_Sample 

type StateA = { Counter: int } 
type StateB = { Counter: int; Pass: bool } 

type DU = 
| A of StateA 
| B of StateB 

而这个C#:

[TestMethod] 
public void TestMethod1() 
{ 
    var stateB = GetStateB(); 
    Assert.IsTrue(stateB.IsB); 
    //Assert.IsTrue(((DU_Sample.StateB)stateB).Pass); // nope 
    //var nutherB = DU_Sample.DU.NewB(stateB); // nope 
    Assert.IsTrue(((dynamic)stateB).Item.Pass); // pass 
} 

private static DU_Sample.DU GetStateB() 
{ 
    var stateB = new DU_Sample.StateB(0, true); 
    return DU_Sample.DU.NewB(stateB); 
} 

我怎么能投的区分联合类型的这部分之一,以访问那部分的属性?

+1

为什么'GetStateB'返回比'StateB'例如其他的东西吗?有多混淆.. – ildjarn

+0

我认为你需要施放'stateB.Item'属性。 –

+1

你有没有试过转换成'DU_Sample.DU.B'? –

在这两种情况下,你必须(下)投再使用属性Item

Assert.IsTrue((stateB as DU_Sample.DU.B)?.Item.Pass ?? false); 
var nutherB = DU_Sample.DU.NewB(((DU_Sample.DU.B)stateB).Item)