我在我的类中使用索引器来更容易地搜索列表。但是,我希望能够返回一个布尔和一个int。不是在同一时间,而是确定它是一个布尔型还是int型,然后返回它。具有多种返回类型的索引器
public class uPermissions
{
private List<uPermission> permissions = new List<uPermission>()
{
new uPermission ("canBuild", false),
new uPermission ("canClaim", false),
new uPermission ("canUnClaim", false),
new uPermission ("canInvite", false),
new uPermission ("canKick", false),
new uPermission ("canSetHome", false)
};
private List<uConstraint> constraints = new List<uConstraint>();
public bool this[string index]
{
get
{
return permissions.Where (p => p.name == index).First().allowed;
}
set
{
permissions.Where (p => p.name == index).First().allowed = value;
}
}
public int this[string index]
{
get
{
return constraints.Where (c => c.name == index).First().count;
}
set
{
constraints.Where (c => c.name == index).First().count = value;
}
}
public bool exists (string permission)
{
var perm = permissions.Where (p => p.name.ToLower() == permission.ToLower()).First();
return (perm != null) ? true : false;
}
public void setAllTrue()
{
foreach (uPermission p in permissions)
{
p.allowed = true;
}
}
public void setAllFalse()
{
foreach (uPermission p in permissions)
{
p.allowed = false;
}
}
}
public class uConstraint
{
public string name;
public int count;
public uConstraint() { }
public uConstraint (string name, int count)
{
this.name = name;
this.count = count;
}
}
public class uPermission
{
public string name;
public bool allowed;
public uPermission() { }
public uPermission (string name, bool allowed)
{
this.name = name;
this.allowed = allowed;
}
}
这是我的代码。我在搜索时看到了一些关于模板的内容,但我不明白它是如何工作的,或者它甚至是正确的解决方案。如果有人可以提供一些见解,将不胜感激
也许你应该考虑字典 - 它会更快。 –
我会使用字典,但这是对另一个软件的扩展,它使用xml来存储数据,但xml解析并不解析字典 –
那么,如何区分何时应该返回布尔,何时int?你在这两种情况下都传递相同的字符串参数。 – Evk