我無法訪問繼承了interface( )IsNameAPalindrome的抽象類 ( ) 的虛擬屬性 ()。PetBase IPet
public interface IPet
{
string Name { get; set; }
}
public abstract class PetBase : IPet
{
public abstract string Name { get; set; }
public virtual bool IsNameAPalindrome
{
get
{
return (Name.Equals(string.Join("", Name.Reverse())));
}
}
}
派生類繼承抽象類 ( PetBase)
public class Bird : PetBase
{
public override string Name { get; set; }
}
public class Cat : PetBase
{
public override string Name { get; set; }
}
public class Dog : PetBase
{
public override string Name { get; set; }
}
public class House : List<IPet>
{
}
IsNameAPalindrome現在,當我在遍歷房屋物件時嘗試訪問屬性( )時,它無法訪問
class Program
{
static void Main(string[] args)
{
House house = BuildHouse();
Print(house);
}
static void Print(House house)
{
// TODO: Print the contents of the house similar to the below.
// Feel free to change or improve upon the table as you see fit.
//Name Palindrome
//Gracie False
//Patches False
//Izzi True
//Missy False
Console.WriteLine("Name Palindrome");
foreach (var item in house)
{
Console.WriteLine( item.Name);
}
}
static House BuildHouse()
{
House house = new House();
house.Add(new Cat()
{
Name = "Gracie"
});
house.Add(new Cat()
{
Name = "Patches"
});
house.Add(new Bird()
{
Name = "Izzi"
});
house.Add(new Dog()
{
Name = "Missy"
});
return house;
}
}
uj5u.com熱心網友回復:
您定義House為List<IPet>,這意味著編譯器會將每個串列元素視為IPet沒有屬性的型別IsNameAPalindrome。
如果成為IsNameAPalindrome該介面合約的一部分是合乎邏輯的,那么簡單的解決方案是添加它:
public interface IPet
{
string Name { get; set; }
bool IsNameAPalindrome { get; }
}
如果這對您沒有意義(而且可能沒有,因為 Palendromes 與成為寵物的概念沒有密切聯系),您可以:
- 將每個
IPet轉換為PetBase以訪問該屬性 - 實作一個新介面,例如
IPalendrome,PetBase也實作了該介面,并轉換為該介面以訪問該方法。
對代碼的更改
第一個選項
Console.WriteLine( ((PetBase)item).IsNameAPalindrome);
第二種選擇
public interface IPalendrome
{
bool IsNameAPalindrome { get; }
}
public abstract class PetBase : IPet, IPalendrome
{
...
}
Console.WriteLine( ((IPalendrome)item).IsNameAPalindrome);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/517263.html
標籤:C#网哎呀访问修饰符
