2009-02-12 7 views
91

यह "नहीं" इंगित करेगा। जो दुर्भाग्यपूर्ण है।क्या सी # कक्षा अपने इंटरफेस से गुण प्राप्त कर सकती है?

[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, 
AllowMultiple = true, Inherited = true)] 
public class CustomDescriptionAttribute : Attribute 
{ 
    public string Description { get; private set; } 

    public CustomDescriptionAttribute(string description) 
    { 
     Description = description; 
    } 
} 

[CustomDescription("IProjectController")] 
public interface IProjectController 
{ 
    void Create(string projectName); 
} 

internal class ProjectController : IProjectController 
{ 
    public void Create(string projectName) 
    { 
    } 
} 

[TestFixture] 
public class CustomDescriptionAttributeTests 
{ 
    [Test] 
    public void ProjectController_ShouldHaveCustomDescriptionAttribute() 
    { 
     Type type = typeof(ProjectController); 
     object[] attributes = type.GetCustomAttributes(
      typeof(CustomDescriptionAttribute), 
      true); 

     // NUnit.Framework.AssertionException: Expected: 1 But was: 0 
     Assert.AreEqual(1, attributes.Length); 
    } 
} 

क्या कक्षा किसी इंटरफ़ेस से गुण प्राप्त कर सकती है? या मैं यहाँ गलत पेड़ भड़क रहा हूँ?

उत्तर

59

नहीं। जब भी एक व्युत्पन्न कक्षा में इंटरफ़ेस या ओवरराइडिंग सदस्यों को लागू करते हैं, तो आपको विशेषताओं को फिर से घोषित करने की आवश्यकता होती है।

यदि आप केवल कंपोनेंट मॉडेल (प्रत्यक्ष प्रतिबिंब नहीं) के बारे में परवाह करते हैं, तो मौजूदा प्रकार (डुप्लिकेशन से बचने के लिए) के गुणों का सुझाव देने का एक तरीका ([AttributeProvider]) है, लेकिन यह केवल संपत्ति और अनुक्रमणक उपयोग के लिए मान्य है।

एक उदाहरण के रूप:

using System; 
using System.ComponentModel; 
class Foo { 
    [AttributeProvider(typeof(IListSource))] 
    public object Bar { get; set; } 

    static void Main() { 
     var bar = TypeDescriptor.GetProperties(typeof(Foo))["Bar"]; 
     foreach (Attribute attrib in bar.Attributes) { 
      Console.WriteLine(attrib); 
     } 
    } 
} 

आउटपुट:

System.SerializableAttribute 
System.ComponentModel.AttributeProviderAttribute 
System.ComponentModel.EditorAttribute 
System.Runtime.InteropServices.ComVisibleAttribute 
System.Runtime.InteropServices.ClassInterfaceAttribute 
System.ComponentModel.TypeConverterAttribute 
System.ComponentModel.MergablePropertyAttribute 
+0

क्या आप इस बारे में निश्चित हैं? MemberInfo.GetCustomAttributes विधि एक तर्क लेता है जो बताता है कि विरासत के पेड़ की खोज की जानी चाहिए या नहीं। –

+3

हम्म। मैंने अभी देखा है कि प्रश्न बेस क्लास से इंटरफेस से गुणों को विरासत में लाने के बारे में है। –

+0

क्या इंटरफ़ेस पर विशेषताओं को रखने का कोई कारण है? –

30

आप एक उपयोगी विस्तार विधि को परिभाषित कर सकते हैं ...

Type type = typeof(ProjectController); 
var attributes = type.GetCustomAttributes<CustomDescriptionAttribute>(true); 

यहाँ विस्तार विधि है:

/// <summary>Searches and returns attributes. The inheritance chain is not used to find the attributes.</summary> 
/// <typeparam name="T">The type of attribute to search for.</typeparam> 
/// <param name="type">The type which is searched for the attributes.</param> 
/// <returns>Returns all attributes.</returns> 
public static T[] GetCustomAttributes<T>(this Type type) where T : Attribute 
{ 
    return GetCustomAttributes(type, typeof(T), false).Select(arg => (T)arg).ToArray(); 
} 

/// <summary>Searches and returns attributes.</summary> 
/// <typeparam name="T">The type of attribute to search for.</typeparam> 
/// <param name="type">The type which is searched for the attributes.</param> 
/// <param name="inherit">Specifies whether to search this member's inheritance chain to find the attributes. Interfaces will be searched, too.</param> 
/// <returns>Returns all attributes.</returns> 
public static T[] GetCustomAttributes<T>(this Type type, bool inherit) where T : Attribute 
{ 
    return GetCustomAttributes(type, typeof(T), inherit).Select(arg => (T)arg).ToArray(); 
} 

/// <summary>Private helper for searching attributes.</summary> 
/// <param name="type">The type which is searched for the attribute.</param> 
/// <param name="attributeType">The type of attribute to search for.</param> 
/// <param name="inherit">Specifies whether to search this member's inheritance chain to find the attribute. Interfaces will be searched, too.</param> 
/// <returns>An array that contains all the custom attributes, or an array with zero elements if no attributes are defined.</returns> 
private static object[] GetCustomAttributes(Type type, Type attributeType, bool inherit) 
{ 
    if(!inherit) 
    { 
    return type.GetCustomAttributes(attributeType, false); 
    } 

    var attributeCollection = new Collection<object>(); 
    var baseType = type; 

    do 
    { 
    baseType.GetCustomAttributes(attributeType, true).Apply(attributeCollection.Add); 
    baseType = baseType.BaseType; 
    } 
    while(baseType != null); 

    foreach(var interfaceType in type.GetInterfaces()) 
    { 
    GetCustomAttributes(interfaceType, attributeType, true).Apply(attributeCollection.Add); 
    } 

    var attributeArray = new object[attributeCollection.Count]; 
    attributeCollection.CopyTo(attributeArray, 0); 
    return attributeArray; 
} 

/// <summary>Applies a function to every element of the list.</summary> 
private static void Apply<T>(this IEnumerable<T> enumerable, Action<T> function) 
{ 
    foreach(var item in enumerable) 
    { 
    function.Invoke(item); 
    } 
} 

अद्यतन:

यहाँ के रूप में एक टिप्पणी में SimonD द्वारा प्रस्तावित एक छोटा संस्करण है:

private static IEnumerable<T> GetCustomAttributesIncludingBaseInterfaces<T>(this Type type) 
{ 
    var attributeType = typeof(T); 
    return type.GetCustomAttributes(attributeType, true). 
    Union(type.GetInterfaces(). 
    SelectMany(interfaceType => interfaceType.GetCustomAttributes(attributeType, true))). 
    Distinct().Cast<T>(); 
} 
+1

यह केवल प्रकार-स्तरीय विशेषताओं को प्राप्त करता है, न कि संपत्तियों, फ़ील्ड या सदस्यों, सही? – Maslow

+17

बहुत अच्छा, मैं व्यक्तिगत रूप से एक छोटी इस के संस्करण, अब का उपयोग करें: (इस प्रकार प्रकार) { वर AttributeType = typeof (टी) निजी स्थिर IEnumerable GetCustomAttributesIncludingBaseInterfaces ; रिटर्न टाइप। गेट कस्टमस्टेट्स (एट्रिब्यूट टाइप, सच्चा)। यूनियन (टाइप.गेटइंटरफेस()। SelectMany (इंटरफ़ेस टाइप => इंटरफ़ेस टाइप करें। गेट कस्टमस्टेट्स (विशेषता टाइप, सत्य))) अलग()। (); } –

+1

@ सिमोनडी .: और आपका रिफैक्टर समाधान तेज़ है। – mynkow

16

इस बारे में ब्रैड विल्सन द्वारा एक लेख: Interface Attributes != Class Attributes

संक्षेप में: कक्षाएं डॉन ' टी इंटरफेस से उत्तराधिकारी, वे उन्हें लागू करते हैं। इसका मतलब यह है कि गुण स्वचालित रूप से कार्यान्वयन का हिस्सा नहीं हैं।

यदि आपको विशेषताओं का उत्तराधिकारी होना है, तो इंटरफ़ेस की बजाय एक सार आधार वर्ग का उपयोग करें।

10

जबकि सी # कक्षा अपने इंटरफेस से गुणों का वारिस नहीं करती है, एएसपी.नेट एमवीसी 3 में बाध्यकारी मॉडल के दौरान एक उपयोगी विकल्प होता है।

आप दृश्य के मॉडल की घोषणा तो इंटरफेस के बजाय ठोस प्रकार है, तो देख सकते हैं और मॉडल बांधने की मशीन विशेषताओं लागू होगी होने के लिए (जैसे, [Required] या [DisplayName("Foo")] इंटरफ़ेस से प्रतिपादन और मॉडल को मान्य होता है:

public interface IModel { 
    [Required] 
    [DisplayName("Foo Bar")] 
    string FooBar { get; set; } 
} 

public class Model : IModel { 
    public string FooBar { get; set; } 
} 
तब ध्यान में रखते हुए

:।

@* Note use of interface type for the view model *@ 
@model IModel 

@* This control will receive the attributes from the interface *@ 
@Html.EditorFor(m => m.FooBar) 
2

यह गुण है कि एक कार्यान्वित इंटरफेस पर मौजूद हो सकता है की विशेषताओं को निकालने के लिए की तलाश में लोगों के लिए अधिक है क्योंकि उन विशेषताओं का हिस्सा नहीं हैं कक्षा, यह आपको उन तक पहुंच प्रदान करेगी। ध्यान दें, मेरे पास एक साधारण कंटेनर क्लास है जो आपको PropertyInfo तक पहुंच प्रदान करती है - जैसा कि मुझे इसके लिए जरूरी था। जैसा कि आपको चाहिए हैक करें। यह मेरे लिए अच्छा काम किया।

public static class CustomAttributeExtractorExtensions 
{ 
    /// <summary> 
    /// Extraction of property attributes as well as attributes on implemented interfaces. 
    /// This will walk up recursive to collect any interface attribute as well as their parent interfaces. 
    /// </summary> 
    /// <typeparam name="TAttributeType"></typeparam> 
    /// <param name="typeToReflect"></param> 
    /// <returns></returns> 
    public static List<PropertyAttributeContainer<TAttributeType>> GetPropertyAttributesFromType<TAttributeType>(this Type typeToReflect) 
     where TAttributeType : Attribute 
    { 
     var list = new List<PropertyAttributeContainer<TAttributeType>>(); 

     // Loop over the direct property members 
     var properties = typeToReflect.GetProperties(); 

     foreach (var propertyInfo in properties) 
     { 
      // Get the attributes as well as from the inherited classes (true) 
      var attributes = propertyInfo.GetCustomAttributes<TAttributeType>(true).ToList(); 
      if (!attributes.Any()) continue; 

      list.AddRange(attributes.Select(attr => new PropertyAttributeContainer<TAttributeType>(attr, propertyInfo))); 
     } 

     // Look at the type interface declarations and extract from that type. 
     var interfaces = typeToReflect.GetInterfaces(); 

     foreach (var @interface in interfaces) 
     { 
      list.AddRange(@interface.GetPropertyAttributesFromType<TAttributeType>()); 
     } 

     return list; 

    } 

    /// <summary> 
    /// Simple container for the Property and Attribute used. Handy if you want refrence to the original property. 
    /// </summary> 
    /// <typeparam name="TAttributeType"></typeparam> 
    public class PropertyAttributeContainer<TAttributeType> 
    { 
     internal PropertyAttributeContainer(TAttributeType attribute, PropertyInfo property) 
     { 
      Property = property; 
      Attribute = attribute; 
     } 

     public PropertyInfo Property { get; private set; } 

     public TAttributeType Attribute { get; private set; } 
    } 
} 
संबंधित मुद्दे