2012-10-05 46 views
0

模型中可能有遞歸屬性嗎?目標是爲每個動作動態構建一個字符串。這是我的工作:模型中的遞歸屬性

public class Action 
{ 
    public int ActionId { get; set; } 
    public int? ParentId { get; set; } 
    public string Name { get; set; } 
    public string ActionName { 
    { 
     get 
     { 
      // example result: 1Ai or 2Bi 
      return .... 
     } 
    } 
} 

List<Action> aList = new List<Action>() { 
    new Action { ActionId = 1, Name = "Step 1" }, 
    new Action { ActionId = 2, Name = "Step 2" }, 
    new Action { ActionId = 3, ParentId = 1, Name = "A" }, 
    new Action { ActionId = 4, ParentId = 1, Name = "B" }, 
    new Action { ActionId = 5, ParentId = 2, Name = "A" }, 
    new Action { ActionId = 6, ParentId = 2, Name = "B" }, 
    new Action { ActionId = 5, ParentId = 3, Name = "i" }, 
    new Action { ActionId = 6, ParentId = 6, Name = "i" } 
} 

回答

0

這當然是可能的(雖然我不會把它稱爲遞歸)。你可以通過在構造函數中傳遞父項來完成。

public class Foo 
{ 
    public Foo(string name) 
    { 
     Name = name; 
    } 

    public Foo(Foo parent, string name) 
    { 
     Name = parent.Name + name; 
    } 

    public string Name {get; set;} 
} 

// 


var foo = new Foo("Step 1"); 
var bar = new Foo(foo, "A"); 

// etc. 

有時,人們喜歡把整個父類的引用在子類中,因此,例如可以與最新版本實時生成的name屬性。

這的確會產生來電的級聯(!所以一定要小心)

public class Foo 
{ 
    string _innerName; 

    public Foo(string name) 
    { 
     _innerName = name; 
    } 

    public Foo(Foo parent, string name) 
    { 
     _innerName = name; 
     _parent = parent; 
    } 

    public string Name 
    { 
     get 
     { 
     return parent == null? _innerName; parent.Name + _innerName; 
     } 
    } 
} 

// 


var foo = new Foo("Step 1"); 
var bar = new Foo(foo, "A"); 

// etc. 
0

有很多方法可以做到這一點,可能的方法之一:

class Program 
    { 
     static List<Action> aList; 

     static void Main(string[] args) 
     { 
      aList = new List<Action>() { 
    new Action { ActionId = 1, Name = "Step 1" }, 
    new Action { ActionId = 2, Name = "Step 2" }, 
    new Action { ActionId = 3, ParentId = 1, Name = "A" }, 
    new Action { ActionId = 4, ParentId = 1, Name = "B" }, 
    new Action { ActionId = 5, ParentId = 2, Name = "A" }, 
    new Action { ActionId = 6, ParentId = 2, Name = "B" }, 
    new Action { ActionId = 5, ParentId = 3, Name = "i" }, 
    new Action { ActionId = 6, ParentId = 6, Name = "i" } 
}; 
      Console.WriteLine(aList[2].ActionName); 
      Console.ReadKey(); 

     } 

     public class Action 
     { 
      public int ActionId { get; set; } 
      public int? ParentId { get; set; } 
      public string Name { get; set; } 
      public string ActionName 
      { 

       get 
       { 
        // example result: 1Ai or 2Bi 
        var parent = aList.Find((p) => p.ActionId == ParentId).ActionId; 
        var child = aList.Find((p) => p.ParentId == ActionId).Name; 
        return String.Format("{0}{1}{2}", parent, Name, child) ; 
       } 
      } 
     } 
    }