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

时间:2016-06-17 19:38:17

标签: f# c#-to-f#

鉴于此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 );  
}

如何将Discriminated Union类型转换为其中一个部分以访问该部分的属性?

1 个答案:

答案 0 :(得分:1)

在这两种情况下,你必须(向下)施放,然后使用属性Item

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