初学者。我试图找到一种方法如何访问数组中的对象的属性而不总是使用“array [0]作为ClassName”,当它们不是同一类型的对象时。不需要详细的答案。你也可以建议/引导我到哪里阅读这些东西,因为也许答案会在我面前,但我不能识别它,因为我是初学者。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vezba_9_object_ecercises
{
class Program
{
static void Main(string[] args)
{
object[] books = new object[2];
books[0] = new SomeBooks("Book_1", "Good", 22);
Console.WriteLine((books[4] as SomeBooks).name); // working
// Console.WriteLine((books[4].name); // not working, how to make it work
books[1] = new OtherBooks("Book_2", "Bad", 2);
Console.WriteLine((books[4] as OtherBooks ).name); // working
// Console.WriteLine((books[4].name); // not working, how to make it work
}
}
public class SomeBooks
{
public SomeBooks(string _name, string _likability, int _numberOfPages)
{
name = _name;
likability = _likability;
numberOfPages = _numberOfPages;
}
public string name { get; set; }
public string likability { get; set; }
public int numberOfPages { get; set; }
}
public class OtherBooks
{
public OtherBooks(string _name, string _likability, int _numberOfAuthors)
{
name = _name;
likability = _likability;
NumberOfAuthors = _numberOfAuthors;
}
public string name { get; set; }
public string likability { get; set; }
public int NumberOfAuthors { get; set; }
}
}
答案 0 :(得分:2)
您可以使SomeBook和OtherBook类继承自Book
基类(或接口)。这将允许您将它们存储在类型为Book[]
而不是object[]
的数组中。您可以通过这种方式访问继承的属性,例如Name和Likability,而无需强制转换。
public class Book
{
public string Name { get; set; }
public string Likability { get; set; }
}
public class SomeBook : Book
{
public int NumberOfPages { get; set; }
}
public class OtherBook : Book
{
public int NumberOfAuthors { get; set; }
}
但是我反对这样做的必要性。问问自己这是否过度设计。你可以只有一个Book类,允许其他值为null。
public class Book
{
public string Name { get; set; }
public string Likability { get; set; }
public int? NumberOfPages { get; set; }
public int? NumberOfAuthors { get; set; }
}
答案 1 :(得分:0)
您的数组类型必须是接口,每个元素的类型必须是继承接口的类。
public interface IBook
{
string Name { get; set; }
string Likability { get; set; }
}
public class SomeBook : IBook
{
public string Name { get; set; }
public string Likability { get; set; }
public int NumberOfPages { get; set; }
}
public class OtherBook : IBook
{
public string Name { get; set; }
public string Likability { get; set; }
public int NumberOfAuthors { get; set; }
}
public class Books
{
public Books()
{
IBook[] books = new IBook[2] {
new SomeBook(),
new OtherBook()
};
for (int i = 0; i < books.Length; i++)
{
switch (books[i].GetType().Name)
{
case "SomeBook":
int numberOfPages = ((SomeBook)books[i]).NumberOfPages;
break;
case "OtherBook":
int numberOfAuthors = ((OtherBook)books[i]).NumberOfAuthors;
break;
}
}
}
}