2013-07-25 25 views
0

與任何簽名功能,我想Python代碼轉換爲C#通用類,使用C#

class fwrapper: 
     def __init_ _(self,function,childcount,name): 
      self.function=function 
      self.childcount=childcount 
      self.name=name 
    class node: 
     def __init_ _(self,fw,children): 
      self.function=fw.function 
      self.name=fw.name 
      self.children=children 
     def evaluate(self,inp): 
      results=[n.evaluate(inp) for n in self.children] 
      return self.function(results) 

我發現很難在C#中實現。 1.在類fwrapper.function中,它可以使用任何簽名的功能。 2.要獲得可以用來提的評價函數的返回類型的函數的返回類型

非常感謝

回答

0

不完全知道你正在嘗試做的,但如果你有這樣的事情:

public class FWrapper<TChild, TResult>{ 

    private int childCount; 
    private string name; 
    private Func<TChild, TResult> function; 

    public Func<TChild, TResult> Function { get { return function; } } 

    public FWrapper(Func<TChild, TResult> Function, int ChildCount, string Name){ 
     this.childCount = ChildCount; 
     this.name = Name; 
     this.function = Function; 
    } 
} 

public class Node<TChild, TResult>{ 

    private FWrapper<TChild, TResult> fw; 
    private IEnumerable<TChild> children; 

    public Node(FWrapper<TChild, TResult> FW, IEnumerable<TChild> Children){ 
     this.fw = FW; 
     this.children = Children; 
    } 

    public IEnumerable<TResult> Evaluate(){ 

     var results = new List<TResult>(); 

     foreach(var c in children){ 
      results.Add(fw.Function(c)); 
     } 

     return results; 
    } 
} 

您現在有一個FWrapper類,它在採用年擄作爲參數的函數,並返回一個TResult和一個Node類,使用相同的TChild和TResult類型,所以,例如,你可以做到這一點(簡單的例子)

//Generic function that takes an int and returns a string 
var func = new Func<int, string>(childInt => { 
    var str = "'" + childInt.ToString() + "'"; 
    return str; 
}); 

var fw = new FWrapper<int, string>(func, 10, "Foobar"); 
var children = new List<int>(){ 1,2,3,4,5,6,7,8,9,10 }; 

var node = new Node<int, string>(fw, children); 
var results = node.Evaluate(); 

foreach(var r in results){ 
    Console.WriteLine(r); 
} 

//'1' 
//'2' 
//.. 
//.. 
//'9' 
//'10' 
0

即時猜測這樣的事情?

class Node { 
    private FWrapper fw; 
    private List<Node> children; 

    public Node(FWrapper fw, List<Node> children){ 
     this.fw = fw; 
     this.children = children; 
    } 

    public Evaluate(Object inp){ 
     var results = from child in children select child.Evaluate(inp); 
     return fw.function(results); 
    } 

} 

它只是一個起點。