2010-03-26 9 views
6

उदाहरण के लिए सामान्य इंटरफ़ेस प्रकार कैसे प्राप्त करें?सी # कैसे जांचें कि कोई वर्ग सामान्य इंटरफ़ेस लागू करता है या नहीं?

इस कोड को मान लीजिए:

interface IMyInterface<T> 
{ 
    T MyProperty { get; set; } 
} 
class MyClass : IMyInterface<int> 
{ 
    #region IMyInterface<T> Members 
    public int MyProperty 
    { 
     get; 
     set; 
    } 
    #endregion 
} 


MyClass myClass = new MyClass(); 

/* returns the interface */ 
Type[] myinterfaces = myClass.GetType().GetInterfaces(); 

/* returns null */ 
Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface<int>).FullName); 

उत्तर

5

आदेश सामान्य इंटरफ़ेस आपको FullName संपत्ति के बजाय नाम संपत्ति उपयोग करने की आवश्यकता प्राप्त करने के लिए:

MyClass myClass = new MyClass(); 
Type myinterface = myClass.GetType() 
          .GetInterface(typeof(IMyInterface<int>).Name); 

Assert.That(myinterface, Is.Not.Null); 
0
MyClass myc = new MyClass(); 

if (myc is MyInterface) 
{ 
    // it does 
} 

या

MyInterface myi = MyClass as IMyInterface; 
if (myi != null) 
{ 
    //... it does 
} 
+0

लेकिन मुझे इस प्रकार की आवश्यकता है, क्योंकि मैं इसे संग्रह में जोड़ रहा हूं। –

1

उपयोग नाम बजाय FullName

प्रकार myinterface = myClass.GetType()। GetInterface (typeof (IMyInterface)। नाम);

0

आप "है" कथन का उपयोग क्यों नहीं करते? इसका परीक्षण करें:

class Program 
    { 
     static void Main(string[] args) 
     { 
      TestClass t = new TestClass(); 
      Console.WriteLine(t is TestGeneric<int>); 
      Console.WriteLine(t is TestGeneric<double>); 
      Console.ReadKey(); 
     } 
    } 

interface TestGeneric<T> 
    { 
     T myProperty { get; set; } 
    } 

    class TestClass : TestGeneric<int> 
    { 
     #region TestGeneric<int> Members 

     public int myProperty 
     { 
      get 
      { 
       throw new NotImplementedException(); 
      } 
      set 
      { 
       throw new NotImplementedException(); 
      } 
     } 

     #endregion 
    } 
संबंधित मुद्दे