模型中是否可以有递归属性?目标是使用每个操作动态构建字符串。这是我正在使用的:
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 :(得分: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.
答案 1 :(得分: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) ;
}
}
}
}