标签: custom-attributes

属性继承与反思

我创建了一个自定义属性来装饰我想在运行时查询的许多类:

[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public class ExampleAttribute : Attribute
{
    public ExampleAttribute(string name)
    {
        this.Name = name;
    }

    public string Name
    {
        get;
        private set;
    }
}
Run Code Online (Sandbox Code Playgroud)

这些类中的每一个都派生自一个抽象基类:

[Example("BaseExample")]
public abstract class ExampleContentControl : UserControl
{
    // class contents here
}

public class DerivedControl : ExampleContentControl
{
    // class contents here
}
Run Code Online (Sandbox Code Playgroud)

我是否需要将此属性放在每个派生类上,即使我将其添加到基类中?该属性被标记为可继承,但是当我执行查询时,我只看到基类而不是派生类.

另一个线程:

var typesWithMyAttribute = 
    from a in AppDomain.CurrentDomain.GetAssemblies()
    from t in a.GetTypes()
    let attributes = t.GetCustomAttributes(typeof(ExampleAttribute), true)
    where attributes != null && attributes.Length > 0 …
Run Code Online (Sandbox Code Playgroud)

c# reflection inheritance attributes custom-attributes

6
推荐指数
1
解决办法
487
查看次数

我可以为属性使用集合初始值设定项吗?

C#中的属性可以与集合初始值设定项一起使用吗?

例如,我想做类似以下的事情:

[DictionaryAttribute(){{"Key", "Value"}, {"Key", "Value"}}]
public class Foo { ... }
Run Code Online (Sandbox Code Playgroud)

我知道属性可以有命名参数,因为这看起来与对象初始化器非常相似,我想知道集合初始化器是否也可用.

c# attributes custom-attributes object-initializers collection-initializer

6
推荐指数
2
解决办法
5965
查看次数

可以仅在自动实现的属性的Setter上设置属性吗?

目前我有这个:

[SomeCustomAttribute]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)

但是,我希望此属性仅装饰setter,而不是getter.有没有办法做到这一点?

c# custom-attributes

6
推荐指数
1
解决办法
423
查看次数

从其他属性的代码中测试属性

是否可以测试另一个属性的代码中是否存在属性?

假设您有以下类定义:

public class Inception {
    [Required]
    [MyTest]
    public int Levels { get; set; }
}
public class MyTestAttribute : ValidationAttribute {
    public override bool IsValid(object o){
        // return whether the property on which this attribute
        // is applied also has the RequiredAttribute
    }
}
Run Code Online (Sandbox Code Playgroud)

... MyTestAttribute.IsValid是否可以确定Inception.Levels是否具有RequiredAttribute?

c# reflection custom-attributes

6
推荐指数
1
解决办法
87
查看次数

数组类型的自定义属性

有人可以请帮助我如何定义类型"字符串数组"的自定义属性,因为我找不到格式来定义数组.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCustomWidget">
        <attr name="myarray" format="string-array"/>
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

这段代码似乎不起作用.什么应该是我的"格式"?

xml android custom-attributes

6
推荐指数
1
解决办法
2347
查看次数

ASP.NET MVC检查Controller或Action中的自定义属性

请考虑以下代码:

public class MyAttribute : Attribute {  }

[MyAttribute]
public class MyControlller : Controller
{
      //...
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个Global Action Filter让我得到一个ActionExecutingContext对象的东西.

我的问题是,在这里,我如何检查请求Controller是否已使用我的自定义进行装饰Attribute.

asp.net-mvc custom-attributes

6
推荐指数
1
解决办法
4953
查看次数

使用CustomAttributes和GetCustomAttributes()的优势

我今天注意到我的intellisense中出现了一些关于System.Type.NET 4.5项目对象的新属性.其中一个叫做CustomAttributes.

我对此很感兴趣,因为我之前已经知道这GetCustomAttributes是最昂贵的反射调用之一(DynamicInvoke当然除此之外).据我了解,每次调用都会GetCustomAttributes导致调用构造函数的属性(以及内存分配).我经常使用单独缓存自定义属性来避免在处理大量类型等时出现性能瓶颈.

所以,我写了一个测试,看看是否CustomAttributes有更高的性能GetCustomAttributes:

static void Main(string[] args)
{
    var sw = Stopwatch.StartNew();

    Debug.WriteLine(typeof(Attributed).GetType());

    for (int i = 0; i < 10000; i++)
    {
        var attrs = typeof(Attributed)
            .CustomAttributes
            .Select(a => a.AttributeType)
            .ToList();
    }

    sw.Stop();
    Debug.WriteLine("Using .NET 4.5 CustomAttributes property: {0}", sw.Elapsed);

    sw = Stopwatch.StartNew();

    for (int i = 0; i < 10000; i++)
    {
        var attrs = typeof(Attributed)
            .GetCustomAttributes(true)
            .Select(a => a.GetType())
            .ToList();
    }

    sw.Stop(); …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection custom-attributes

6
推荐指数
1
解决办法
2240
查看次数

检查通用接口成员是否为"纯粹"(具有纯属性)

我有一个接口,其方法使用以下Pure属性进行注释System.Diagnostics.Contracts:

public interface IFoo<T> {
    [Pure]
    T First { get; }

    [Pure]
    T Last { get; }

    [Pure]
    T Choose();

    void Add(T item);

    T Remove();
}
Run Code Online (Sandbox Code Playgroud)

我希望遍历接口的成员并检查成员是否是纯粹的.目前我无法从会员信息中获取任何属性:

var type = typeof(IFoo<>);
var memberInfos = type.GetMembers();
var memberInfo = memberInfos.First(); // <-- Just select one of them
var attributes = memberInfo.GetCustomAttributesData(); // <-- Empty
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

请注意,我没有类或实例.只有界面.

c# generics reflection interface custom-attributes

6
推荐指数
1
解决办法
196
查看次数

在自定义属性中传递自定义参数 - ASP.NET MVC

我的目标是创建一个自定义属性,如System.ComponentModel.DataAnnotations.Display,它允许我传递一个参数.

例如:在System.ComponentModel.DataAnnotations.Display中,我可以将值传递给参数Name

[Display(Name = "PropertyName")]
public int Property { get; set; }
Run Code Online (Sandbox Code Playgroud)

我想做同样的事情,但在控制器和行动如下

[CustomDisplay(Name = "Controller name")]
public class HomeController : Controller
Run Code Online (Sandbox Code Playgroud)

然后使用其值填充ViewBag或ViewData项.

有人可以帮我弄这个吗?

谢谢.

c# asp.net-mvc custom-attributes

6
推荐指数
1
解决办法
6205
查看次数

是否可以向ExpandoObject实例的生成成员添加属性?

我正在尝试使用ExpandoObject作为PropertyGrid的SelectedObject.我知道如何将我想要的属性添加到ExpandoObject:

public dynamic MakePropertyObject()
{
    dynamic expando = new ExpandoObject();
    var dictionary = expando as IDictionary<string, object>;
    foreach(MyClass m in PropertiesINeedToAdd)
        dictionary[m.Name] = m.Value;
    return expando;
}
Run Code Online (Sandbox Code Playgroud)

此代码工作正常 - 调试器expando按预期显示属性的名称和值.

然而,没有生成的属性被显示出来PropertyGrid中的当我设置的返回值MakePropertyObject()到它的SelectedObject属性.我认为(也许是错误地),这是因为ExpandoObject的属性没有任何DisplayNameAttribute,DescriptionAttribute或任何用于控制其他属性如何属性显示在一个PropertyGrid.

我做了一些阅读和一些谷歌搜索,我无法弄清楚是否有一种方法来装饰ExpandoObject自定义属性的生成属性.有谁知道如何做到这一点,或者更好的方式来展示ExpandoObject一个PropertyGrid

解:

@Stephen Cleary提供的答案是正确和有用的(谢谢,斯蒂芬).对于有同样问题的其他人来说,实施ICustomTypeDescriptor对我来说非常合适.

作为旁注,实现的对象ICustomTypeDescriptor为自身提供属性和事件描述符,而不是为另一个对象提供.我认为描述符和描述的内容应该首先通过属性或某种东西相关联 - 对我来说,一个对象应该描述它自己的类型似乎令人困惑和多余,但这确实是如何PropertyGrid使用ICustomTypeDescriptor接口的.

.net propertygrid custom-attributes expando expandoobject

5
推荐指数
1
解决办法
3633
查看次数