C# 带私有setter的列表
我试图让我的类的用户能够添加到列表中,而不是设置。因此,我希望有一个这样的私人设置:C# 带私有setter的列表,c#,linq,list,C#,Linq,List,我试图让我的类的用户能够添加到列表中,而不是设置。因此,我希望有一个这样的私人设置: public class Model { private IList<KeyValuePair<string, int>> pair; public Model() { pair = new List<KeyValuePair<string, int>>(); } public IList<KeyV
public class Model
{
private IList<KeyValuePair<string, int>> pair;
public Model()
{
pair = new List<KeyValuePair<string, int>>();
}
public IList<KeyValuePair<string, int>> Pair
{
get
{
return pair.Where(x => x.Value > 0
&& !string.IsNullOrEmpty(x.Key)).ToList();
}
private set { pair = value; }
}
如果要使用此方法,可能需要在此类中实现公共Add方法,以便将元素添加到基础私有属性:
public class Model
{
// Other code omitted for brevity
public bool Add(KeyValuePair<string,int>> item)
{
// Add your item to the underlying list
pair.Add(item);
}
}
您可能正在使用模型的结果。Pair并试图添加到其中,这将无法像模型那样工作。Pair只返回列表的副本,而不是实际的列表本身。如果您想使用此方法,您可能希望在此类中实现公共Add方法,以便将元素添加到基础私有属性:
public class Model
{
// Other code omitted for brevity
public bool Add(KeyValuePair<string,int>> item)
{
// Add your item to the underlying list
pair.Add(item);
}
}
您可能正在使用模型的结果。Pair并试图添加到其中,这不会像模型那样工作。Pair只返回列表的副本,而不是实际的列表本身。我可能会用一种方法解决它
public class Model
{
private readonly Dictionary<string, int> pairs = new Dictionary<string, int>();
public void Add(string key, int value)
{
pairs[key] = value;
}
public IEnumerable<KeyValuePair<string, int>> GetPairs()
{
return from pair in pairs
where pair.Value > 0 && string.IsNullOrEmpty(pair.Key) == false
select pair;
}
}
我可能会用一种方法解决它
public class Model
{
private readonly Dictionary<string, int> pairs = new Dictionary<string, int>();
public void Add(string key, int value)
{
pairs[key] = value;
}
public IEnumerable<KeyValuePair<string, int>> GetPairs()
{
return from pair in pairs
where pair.Value > 0 && string.IsNullOrEmpty(pair.Key) == false
select pair;
}
}
在c6中,您不需要私有setter。仍然可以在构造函数中设置,并且只能在构造函数中设置。在这种情况下,我可能会创建一个函数而不是使用属性。因此,您希望用户添加任何值,但当他们查询值时,您希望能够对其进行筛选,对吗?Pair返回一个新的临时列表,它是另一个列表的副本。你可以添加到那个列表中。它现在有更多的项目!万岁!然后它就消失了,就像雨中的泪水。时间删除所有成对的linq垃圾。Get不能使用c 6。4.5.2@Yacoub马萨德-是的,在C 6中,你不需要二等兵。仍然可以在构造函数中设置,并且只能在构造函数中设置。在这种情况下,我可能会创建一个函数而不是使用属性。因此,您希望用户添加任何值,但当他们查询值时,您希望能够对其进行筛选,对吗?Pair返回一个新的临时列表,它是另一个列表的副本。你可以添加到那个列表中。它现在有更多的项目!万岁!然后它就消失了,就像雨中的泪水。时间删除所有成对的linq垃圾。Get不能使用c 6。4.5.2@Yacoub马萨德-是的