c# - 如何从程序集级属性引用私有(private)类的类型?

标签 c# attributes class-attributes

我定义了一个程序集级别的属性类 FooAttribute,如下所示:

namespace Bar
{
    [System.AttributeUsage (System.AttributeTargets.Assembly, AllowMultiple=true)]
    public sealed class FooAttribute : System.Attribute
    {
        public FooAttribute(string id, System.Type type)
        {
            // ...
        }
    }
}

我用它将 id 关联到类,例如:

[assembly: Bar.Foo ("MyClass", typeof (Bar.MyClass))]

namespace Bar
{
    public class MyClass
    {
        private class Mystery { }
    }
}

一切正常。但是,如果我需要以某种方式引用 MyClass 中定义的私有(private)类 Mystery 怎么办?这是可能吗?尝试从顶级 [assembly: ...] 指令引用它不起作用,因为该类型不公开可见:

[assembly: Bar.Foo ("Mystery", typeof (Bar.MyClass.Mystery))] // won't work

并试图将 [assembly: ...] 指令放入 MyClass 中,以便它可以看到 Mystery 是不合法的,因为 [assembly: ...] 必须在顶层定义:

namespace Bar
{
    class MyClass
    {
        [assembly: FooAttribute (...)] // won't work either
        ...
    }
}

有一种方法可以通过将用户声明为程序集的 friend 来从程序集外部访问内部 类型,但是如何在程序集中引用私有(private)类型呢?我想这是不可能的,我只需要将 Mystery 声明为 internal 即可,但我想确保我没有遗漏一些细微之处。

最佳答案

让它成为 internal(您已经声明您不想这样做)是最省力的方法。对于大多数代码,允许 MyClass 公开(通过静态属性)type 实例(即 public static Type MysteryType { get { return typeof(Mystery) ; } 会工作,但不会对属性工作(只能使用一些基本类型的常量值)。

internal 的唯一替代方法是将其编码为字符串文字,(即 [Foo("Bar.MyClass+Mystery") ]) 并使用 typeof(MyClass).Assembly.GetType(fullName) - 但随后您将失去 typeof 通常提供的编译器验证。 (还要注意运行时用来表示嵌套类型的 +,而不是 .,它是 C# 表示)

就我个人而言,我只是将其设为内部

关于c# - 如何从程序集级属性引用私有(private)类的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7240500/

相关文章:

c# - 将字典键设置为对象类型

vim - YouCompleteMe 不可用 : module 'collections' has no attribute 'Mapping'

c# - DebuggerDisplay 在运行时解析为字符串

python - 在类体内使用非局部或全局

python - 未找到 load_resource 函数作为 FPDF 的类方法

C# - 值类型等于方法 - 为什么编译器使用反射?

c# - 用于 Mac/Windows 文件的 MySqlBulkLoader

c# - 复杂类型参数属性未发生 Web Api 数据注释验证

java - 放冒号(:) in xml attribute

python - 如何从 Python 中的被调用函数访问调用方方法的 __class__ 属性?