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

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

问题描述

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

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

例如:

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

[MyAttribute]
class TargetClass
{
}

推荐答案

不是直接的,但是为了让属性做任何事情,你必须已经拥有类型/成员的句柄并调用它的 GetCustomAttributescode> 方法,所以你可以简单地从那里传入它:

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)
    {
    }
}

像这样使用它:

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

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

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