无法在 C# 中转换 F# 对象

Unable to cast an F# Object in 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 );  
}

如何将可区别联合类型转换为它的一个部分以访问该部分的属性?

在这两种情况下,您都必须(向下)转换然后使用 属性 Item

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