Custom Assembly Attribute to String

半世苍凉 提交于 2019-12-14 04:07:27

问题


I have defined a custom assembly attribute and am trying to call it into a string much like my previous post Calling Custom Assembly Attributes. I am now trying to accomplish the very same thing in c#.

I have defined my custom attribute:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;

namespace authenticator.Properties
{
    public class SemverAttribute : Attribute
    {
        private string _number;

        public string getversion
        {
            get {return _number;}
        }

        public SemverAttribute(string Number)
        {
            _number = Number;
        }
    }
}

And am attempting to call it with:

// Define the semver version number
Assembly assy = Assembly.GetExecutingAssembly();
object[] attr = null;
attr = assy.GetCustomAttributes(typeof(SemverAttribute), false);
if (attr.Length > 0)
  {
    ViewBag.Version = attr[0].getversion;
  }
else
  {
    ViewBag.Version = string.Empty;
  }

However when trying to build I get:

'object' does not contain a definition for 'getversion' and no extension method 'getversion' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Any help on this would be much appreciated.


回答1:


you just need a cast, as Assembly.GetCustomAttributes(xxx) return type is Object[]

so

ViewBag.Version = (attr[0] as SmverAttribute).getversion;

EDIT

this could be rewritten like that (for example)

var attribute = Assembly.GetExecutingAssembly()
                        .GetCustomAttributes(false)
                        .OfType<SemverAttribute>()
                        .FirstOrDefault();

ViewBag.version = (attribute == null)
                  ? string.Empty
                  : attribute.getversion;


来源:https://stackoverflow.com/questions/24046058/custom-assembly-attribute-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!