سؤال

أحتاج إلى أن أكون قادرا على استرداد السمات المخصصة للفئة من طريقة في فئتها الأساسية. الآن أنا أفعل ذلك عبر طريقة ثابتة محمية في الفئة الأساسية مع التنفيذ التالي (يمكن أن يكون للفئة مثيلات متعددة من نفس السمة المطبقة):

//Defined in a 'Base' class
protected static CustomAttribute GetCustomAttribute(int n) 
{
        return new StackFrame(1, false) //get the previous frame in the stack
                                        //and thus the previous method.
            .GetMethod()
            .DeclaringType
            .GetCustomAttributes(typeof(CustomAttribute), false)
            .Select(o => (CustomAttribute)o).ToList()[n];
}

أنا أسميها من فئة مشتقة، وبالتالي

[CustomAttribute]
[CustomAttribute]
[CustomAttribute]
class Derived: Base
{
    static void Main(string[] args)
    {

        var attribute = GetCustomAttribute(2);

     }

}

من الناحية المثالية، سأكون قادرا على الاتصال بهذا من الملحقات وتخزين المؤقتات.

شكرا.

ملاحظة

أدرك أن GetCustomattributes غير مضمون لإعادتها فيما يتعلق بالترتيب المعجمي.

هل كانت مفيدة؟

المحلول

إذا كنت تستخدم أساليب المثيل بدلا من الأساليب الثابتة، فيمكنك الاتصال بهذا. اجعلت TiseType ()، حتى من الفئة الأساسية.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
class CustomAttribute : Attribute
{}

abstract class Base
{
    protected Base()
    {
        this.Attributes = Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute))
            .Cast<CustomAttribute>()
            .ToArray();
    }

    protected CustomAttribute[] Attributes { get; private set; }
}

[Custom]
[Custom]
[Custom]
class Derived : Base
{
    static void Main()
    {
        var derived = new Derived();
        var attribute = derived.Attributes[2];
    }
}

إنه أبسط، وينجز التخزين المؤقت في المنشئ أنك تأمل في ذلك.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top