SORU
12 ŞUBAT 2009, PERŞEMBE


Bir C# sınıf arayüzü özniteliklerini devralır?

Bu ima görünür"". hayır Çok yazık.

[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);
    }
}

Bir sınıf bir arabirim öznitelikleri devralabilir? Ya yanlış ağaca havlıyor burada?

CEVAP
12 ŞUBAT 2009, PERŞEMBE


Hayır. Bir arabirim ya da türetilmiş bir sınıfta geçersiz kılma üyeleri uygulamak ne zaman yeniden bildirmek için gereken nitelikler.

Eğer sadece bakım hakkında ComponentModel (doğrudan yansıması), bir şekilde ([AttributeProvider]) düşündüren nitelikler varolan türü (tekrarını önlemek için), ama sadece geçerli özellik ve oluşturucu kullanımı.

Örnek olarak:

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);
        }
    }
}

çıkışlar:

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

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Sam Kear

    Sam Kear

    14 Temmuz 2007
  • TechXCentral

    TechXCentral

    12 Temmuz 2011
  • WiseOwlTutorials

    WiseOwlTutor

    21 EKİM 2011