自组装属性为String [英] Custom Assembly Attribute to String

查看:145
本文介绍了自组装属性为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个自定义组件的属性,我试图把它叫成字符串很像我的previous后的调用自定义程序集属性。我现在想实现在C#中同样的事情。

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

和在尝试与调用它:

// 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:

对象不包含getversion'和一个没有定义
  扩展方法getversion接受式的第一个参数
  对象可以找到(是否缺少using指令或程序
  集引用?)

'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?)

任何帮助将是非常美联社preciated。

Any help on this would be much appreciated.

推荐答案

您只需要一个转换,如 Assembly.GetCustomAttributes(XXX)返回类型为 [对象]

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

所以

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

修改

此可以改写像(例如)

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

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

这篇关于自组装属性为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆