我正在嘗試在下面的主類中撰寫代碼。我需要的是:字串格式。
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World");
List<Person> human = new List<Person>()
{
new Person("Sarah", 18), new Person("Peter", 33),
new Person("Paul", 29), new Child("Kevin", 15, true), new Child("Maria", 9, false)
};
}
//
class Person
{
public string Firstname { get; set; }
public int Age { get; set; }
public Person(string fn, int ag)
{
this.Firstname = fn;
this.Age = ag;
}
}
//
class Child : Person
{
public bool IsMale { get; set; }
public Child(string fn, int ag, bool isM) : base(fn, ag)
{
this.IsMale = isM;
}
}
////new feature:
public virtual string CalMe()
{
return "Hiii";
}
}
您能否在評論中更正我的答案或在那里寫一個新答案?謝謝
uj5u.com熱心網友回復:
我不反對 Dmitry 的回答,但我認為將檢查合并為一個可能會使代碼更流暢地閱讀
human.Where(h => h is Child c && !c.IsMale)
至于為什么你的嘗試沒有奏效;并非串列中的每個元素都是 Child(一個 Child 是一個 Person,但不一定反過來)-它們都能夠像 Person 一樣行事,但是要成為 Child 需要先進行強制轉換,然后才能訪問僅可用的屬性在孩子身上
您已經對問題進行了大量編輯,但沒有給出任何新標準的說明。模式保持不變:
cars.Where(c => c is SubCar sc && sc.SomeSubCarOnlyProperty == someValue
uj5u.com熱心網友回復:
您可以嘗試OfType()構造來過濾掉s 中的所有Children Person:
var femaleChildren = human
.OfType<Child>() // children only
.Where(child => !child.IsMale); // which are not male
foreach (var child in femaleChildren)
Console.WriteLine($"{child.Firstname} {child.Age}");
編輯:如果你不想使用OfType,你可以把Select和Where:
var femaleChildren = human
.Select(item => item as Child) // either Child or null
.Where(item => item != null) // children only, no nulls
.Where(child => !child.IsMale); // which are not male
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399239.html
