C#属性可以访问目标类? [英] Can C# Attributes access the Target Class?

查看:113
本文介绍了C#属性可以访问目标类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过使用反射来访问从属性类的类的属性。这可能吗?

例如:

 类MyAttribute:属性
{
    私人无效AccessTargetClass()
    {
        //做一些操作
    }
}[MyAttribute]
类TargetClass
{
}


解决方案

不是直接的,而是为了让属性做任何事,你已经必须有一个句柄类型/成员并调用它的 GetCustomAttributes 方法,这样你就可以简单地从那里将它传递:

 类MyAttribute:属性
{
    公共无效DoSomethingWithDeclaringType(T型)
    {
    }
}

使用它像这样:

 键入classType所= typeof运算(MyClass的);
[对象] attribs = classType.GetCustomAttributes(typeof运算(MyAttribute),TRUE);
如果(attribs.Length大于0)
{
    ((MyAttribute)attribs [0])DoSomethingWithDeclaringType(classType所)。
}

I want to access the properties of a class from the attribute class by using reflection. Is it possible?

For example:

class MyAttribute : Attribute
{
    private void AccessTargetClass()
    {
        // Do some operations
    }
}

[MyAttribute]
class TargetClass
{
}

解决方案

Not directly, but in order for the attribute to do anything, you already must have a handle to the type/member and call its GetCustomAttributes method, so you can simply pass it in from there:

class MyAttribute : Attribute
{
    public void DoSomethingWithDeclaringType(Type t)
    {
    }
}

Using it like so:

Type classType = typeof(MyClass);
object[] attribs = classType.GetCustomAttributes(typeof(MyAttribute), true);
if(attribs.Length > 0)
{
    ((MyAttribute)attribs[0]).DoSomethingWithDeclaringType(classType);
}

这篇关于C#属性可以访问目标类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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