在我开始从事的一个新项目中自己学习 C#,
其中一种方法,接受List<string>
类型数据,作为参数传入
。我现在想知道...需要两个这些列表、两种类型的数据或两个组,
就这个例子来说,假设我有优点和缺点,或者..女孩和男孩>,
这些实际上是两个独立的元素或对象列表,我需要作为参数传入
,我希望它作为一个数据类型传递,然后,在方法内部我将负责数据列表的分离,所以..而不是几个 List
对象我,认为(有一秒钟,Dictionary
将是合适的......)
虽然我只有一个元素(一个项目...每个都是 List
),但在我需要传递的这种数据类型中
我该怎么做才能得到这个结果?
我会尝试说明它:
List<string> classGirls = new List<string>();
List<string> classBoys = new List<string>();
对于源中的 eace 项目...从源加载两者
完成 列表女孩 + 列表男孩已填充,您如何将它们作为一个字典传递,但知道您只会有一个女孩和一个男孩列表对象吗?
public bool foundAMatch( string Lookup, List<string> G , List<string> B){
{
var firstGirl = G.ElementAt(0);
var firstBoy = B.ElementAt(0);
return firstGirl == Lookup && firstBoy !=Lookup ;
}
相反,我需要它像这样
public bool foundAmatch(string Lookup, someDataType.... Kids)
{
var firstGirl = kids-girls <-- first entity in kids;
var firstBoy = kids-boys <-- first entity in Kids;
return firstGirl == Lookup && firstBoy !=Lookup ;
}
很少有事情要记住...至于数据的属性,它应该具有良好的性能...自然期望的,但最重要的是,它应该是适当的/易于安排并适合使用循环进行排序和作为主题的迭代到各种统计操作。
- 问题是,
您将如何实现逻辑,它是我正在考虑的现有数据类型吗?
如果不是,在这种情况下您将采用什么方法来选择/创建数据类型?
最佳答案
您可以通过使用继承轻松解决这个问题:
public abstract class Person
{
public string Name { get; private set; } // The setter is private because we only have to set this name when we create an instance
protected Person(string name)
{
Name = name;
}
}
public class Male : Person
{
public Male(string name) : base(name) // This constructor calls the constructor of the class it inherits and passes on the same argument
}
public class Female : Person
{
public Female(string name) : base(name)
}
public bool IsMatch(string needle, IEnumerable<Person> haystack)
{
var firstGirl = haystack.OfType<Female>().FirstOrDefault();
var firstBuy = haystack.OfType<Male>().FirstOrDefault();
return firstGirl != null &&
firstGirl.Name == needle &&
firstBoy != null &&
firstBoy.Name != needle;
}
编辑:
我非常喜欢扩展方法,所以我会这样编写方法:
public static class PersonExtensions
{
public static bool IsMatch(this IEnumerable<Person> haystack, string needle)
{
// same method logic in here
}
}
然后你可以这样使用:
var people = new List<Person>();
people.Add(new Male { Name = "Bob" });
people.Add(new Female { Name = "Mary" });
var isMatch = people.IsMatch("Jane");
编辑2:
将性别作为 Person
类的属性可能会更好:
public enum Sex
{
Male,
Female
}
public class Person
{
public string Name { get; private set; }
public Sex Gender { get; private set; }
public Person(string name, Sex gender)
{
Name = name;
Gender = gender;
}
}
并将方法更改为:
var firstGirl = haystack.FirstOrDefault(p => p.Gender == Gender.Female);
var firstBoy = haystack.FirstOrDefault(p => p.Gender == Gender.Male);
关于c# - 适合一对 List <string> 对象的数据类型,作为一个容器来容纳这两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13955859/