C# 选中特定索引处列表中的列表不为空
如何访问下面列表1中的列表2并在断言中检查IsnotNullC# 选中特定索引处列表中的列表不为空,c#,C#,如何访问下面列表1中的列表2并在断言中检查IsnotNull List<Object> list1= new List<Object>(); List<int> list2= new List<int>(); list1.add(someValue); list1.add(list2); Assert.IsNotNull(list1[1]..??); 以下是方法: ((List<int>)list1[1]).<someth
List<Object> list1= new List<Object>();
List<int> list2= new List<int>();
list1.add(someValue);
list1.add(list2);
Assert.IsNotNull(list1[1]..??);
以下是方法:
((List<int>)list1[1]).<something>
但是请使用一些合适的变量名。此外,列表是一种巨大的代码气味。@RobIII在他的回答中展示了如何将对象值转换为列表;然而,真正的问题是,您如何知道列表1中哪个位置包含什么?您将得到一个类似于以下代码的代码:
for (int i = 0; i < list1.Count; i++) {
object item = list1[i];
switch (item)
{
case int x:
// do some thing with x
break;
case string s:
// do some thing with s
break;
case IList list:
// do some thing with list
break;
....
}
}
这将变得单调乏味
更好的方法是以面向对象的方式工作。范例
public abstract class Property
{
public string Name { get; set; }
public abstract void DoSomething();
}
public abstract class Property<T> : Property
{
public T Value { get; set; }
}
public class StringProperty : Property<string>
{
public override void DoSomething() =>
Console.WriteLine($"String of length {Value?.Length}");
}
public class IntListProperty : Property<List<int>>
{
public override void DoSomething() =>
Console.WriteLine($"Int list has {Value?.Count} items");
}
现在你可以写作了
var list1 = new List<Property>{
new StringProperty { Name = "string property", Value = "hello" },
new IntListProperty { Name = "Int list", Value = new List<int>{ 2, 3, 5, 7 } }
};
for (int i = 0; i < list1.Count; i++) {
Property prop = list1[i];
Console.Write(prop.Name); Console.Write(": ");
prop.DoSomething();
}
这就是所谓的多态性。这意味着多形。您有不同形状的属性,但它们都有名称和剂量测量方法。您可以对不同类型的属性调用此方法,并将要执行的不同操作委托给这些属性。每个人都知道它必须做什么。list1[1]是访问list2的方式。现在还不清楚你的问题是什么。为什么你要把不同的元素放在同一个列表中呢?那就是缺少软件设计,甚至连数据模型的外表都没有-这起作用了。非常感谢。