Custom Assembly Attribute to String

2019-09-08 11:31发布

问题:

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;