2014-02-12 60 views
4

爲什麼當t是派生接口時,typeof(t).GetProperties()沒有找到t的所有公共屬性?這是預期的行爲還是我錯過了某些東西?typeof(t).GetProperties()當t是從另一個接口派生的接口

public interface IBaseOne 
    {  int Id { get; } } 

public interface IDerivedOne : IBaseOne 
    {  string Name { get; } } 

public class ImplementsIDerivedOne : IDerivedOne 
    { 
     public int Id { get; private set; } 
     public string Name { get; private set; } 
    } 

public static class TypeOfTests 
    { 
     public static Type Testing<T>() where T : class,IBaseOne 
     { 
      return typeof(T); 
     } 
    } 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Type typeFromIBaseOne = TypeOfTests.Testing<IBaseOne >() ; 
     Type typeFromIDerivedOne = TypeOfTests.Testing<IDerivedOne>(); 
     Type typeFromImplementsIDerivedOne = TypeOfTests.Testing<ImplementsIDerivedOne>(); 

     PropertyInfo[] propsFromIBaseOne = typeFromIBaseOne.GetProperties(); 
     PropertyInfo[] propsFromIDerivedOne = typeFromIDerivedOne.GetProperties(); 
     PropertyInfo[] propsFromImplementsIDerivedOne =TypeFromImplementsIDerivedOne.GetProperties(); 

     Debug.Print("From IBaseOne: {0} properties", propsFromIBaseOne.Length); 
     Debug.Print("From IDerivedOne: {0} properties", propsFromIDerivedOne.Length); 
     Debug.Print("From ImplementsIDerivedOne: {0} properties", propsFromImplementsIDerivedOne .Length); 
    } 
} 

結果: 從IBaseOne:1個性能 從IDerivedOne:1個性能 從ImplementsIDerivedOne:2個性能

爲什麼IDerivedOne只顯示1分財產?

謝謝

恩裏克

回答

5

這是因爲接口不從一個又一個「派生」;把它們視爲實施班級必須遵守的合同。因此,當你有這樣的:

interface IFoo : IBar { } 

這並不意味着IFoo本身具有相同的成員,IBar一樣。這意味着的任何實施者IFoo也承擔實施IBar的責任。從實施者的角度來看,這種區別可能聽起來不錯,但它對類型系統確實產生了非常重要的影響。

如果你想專門找出其性質必須通過的IDerivedOne代替哪些屬性IDerivedOne的實現者定義聲明你將不得不反思IDerivedOne,找到它的「基地」接口和遞歸地枚舉其成員。

+0

感謝您的回答。現在很清楚。恩裏克 – user2230803