【问题标题】:Why doesn't this reflection return Custom Attributes from the assembly?为什么此反射不从程序集中返回自定义属性?
【发布时间】:2014-05-12 22:26:20
【问题描述】:

我正在学习如何使用自定义属性将元信息添加到我的参数类。我正在关注一本名为“Professional C# 5.0”的教科书中的示例。

以下是嵌入在测试夹具中的完整程序。 Assert 语句应该返回一个大于 0 的值;但事实并非如此。我很困惑为什么。请协助。下面的代码是自包含的:创建一个新的类库项目并确保你有一个对 NUnit 的引用来运行单元测试。另一方面,如果您是专家,您可能只需阅读代码并给我反馈。

using System;
using System.Reflection;
using NUnit.Framework;

namespace GameDesigner.Sandbox.TestFixtures
{
    [TestFixture]
    internal class DeclarativeAttributesTestFixture
    {
        [Test]
        public void UseReflectionToFindNumericAttributes()
        {
            Assembly theAssembly = typeof (PhaseState).Assembly;

            Assert.AreEqual("GameDesigner.Sandbox, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            theAssembly.FullName);

            Attribute[] supportingAttributes = Attribute.GetCustomAttributes(theAssembly, typeof(OptimizableNumeric));

            Assert.IsTrue(supportingAttributes.Length > 0, "supportingAttributes was length: " + supportingAttributes.Length);
        }
    }


    public class PhaseState
    {
        public PhaseState(double temperatue, int pressure, string state)
        {
            Temperature = temperatue;
            Pressure = pressure;
            State = state;
        }

        [OptimizableNumeric(0.0, 300.0, 1.0)] public double Temperature;

        [OptimizableNumeric(1.0, 10.0, 1.0)] public int Pressure;

        [OptimizableNominal(new string[] {"solid", "liquid", "gas"})] public string State;
    }

    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
    public class OptimizableNumeric : Attribute
    {
        private readonly double _start;
        private readonly double _stop;
        private readonly double _stepSize;

        public OptimizableNumeric(double start, double stop, double stepSize)
        {
            _stepSize = stepSize;
            _stop = stop;
            _start = start;
        }

        public double Start
        {
            get { return _start; }
        }

        public double Stop
        {
            get { return _stop; }
        }

        public double StepSize
        {
            get { return _stepSize; }
        }
    }

    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
    public class OptimizableNominal : Attribute
    {
        private readonly string[] _nominalList;


        public OptimizableNominal(string[] nominalList)
        {
            _nominalList = nominalList;
        }

        public string[] NominalList
        {
            get { return _nominalList; }
        }
    }
}

我尝试了许多不同的示例来说明如何检索自定义属性,但都没有生成结果。由于我从教科书中复制而对我在做什么没有任何理解,因此我很难诊断代码。

【问题讨论】:

    标签: c# reflection custom-attributes


    【解决方案1】:

    Attribute[] GetCustomAttributes(Assembly element, Type attributeType) 方法返回自定义属性数组应用于程序集。应用于程序集的属性看起来像

    [assembly: AssemblyCompany("Microsoft")]
    

    您的属性不适用于程序集。使用以下代码获取应用于State 字段的自定义属性:

    var memberInfo = typeof(PhaseState).GetField("State");
    Attribute[] supportingAttributes = 
      Attribute.GetCustomAttributes(memberInfo, typeof(OptimizableNominalAttribute));
    

    如果要检查程序集中具有此属性的所有公共成员,可以使用以下查询:

    var attributeType = typeof(OptimizableNominalAttribute);
    
    var supportingAttributes = theAssembly.GetTypes()
              .SelectMany(t => t.GetMembers()) // you can pass binding flags here
              .SelectMany(m => Attribute.GetCustomAttributes(m, attributeType));
    

    查询语法:

    var supportingAttributes = 
          from t in theAssembly.GetTypes()
          from m in t.GetMembers()
          from a in Attribute.GetCustomAttributes(m, attributeType)
          select a;
    

    【讨论】:

      猜你喜欢
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      相关资源
      最近更新 更多