如果当它们被反射到属性只建造,为什么属性构造如此有限? [英] If attributes are only constructed when they are reflected into, why are attribute constructors so limited?

查看:96
本文介绍了如果当它们被反射到属性只建造,为什么属性构造如此有限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如所示<一href=\"http://stackoverflow.com/questions/1168535/when-is-a-custom-attributes-constructor-run\">here,属性构造函数不叫,直到你反映来获得属性值。然而,正如你可能也知道,你只能通过编译时常值属性的构造函数。为什么是这样?我想很多人会 preFER做这样的事情:

As shown here, attribute constructors are not called until you reflect to get the attribute values. However, as you may also know, you can only pass compile-time constant values to attribute constructors. Why is this? I think many people would much prefer to do something like this:

[MyAttribute(new MyClass(foo, bar, baz, jQuery)]

不是传递一个字符串(导致stringly输入code呢!)与价值观,变成字符串,然后依靠正则表达式,试图获得价值,而不是仅仅使用实际值,而不是使用编译根据例外 - 时间警告/错误可能被某处无关带班,除了抛出一个,它调用的方法使用了被输入错误的一些属性。

than passing a string (causing stringly typed code too!) with those values, turned into strings, and then relying on Regex to try and get the value instead of just using the actual value, and instead of using compile-time warnings/errors depending on exceptions that might be thrown somewhere that has nothing to do with the class except that a method that it called uses some attributes that were typed wrong.

限制是什么造成的?

推荐答案

属性是的元数据的一部分。你需要能够的反映的上装配的没有元数据在装配运行code

Attributes are part of metadata. You need to be able to reflect on metadata in an assembly without running code in that assembly.

想象一下,比如你正在编写编译器,需要以编译一些源$ C ​​$ C读取从一个程序集的属性。你真的想在引用的程序集的code是的加载和执行的?你想放的需求的编译器上的作家,他们写的,可以的编译的过程中运行的引用程序任意code编译器? code,可能会崩溃,或者进入无限循环,或者说,开发商无权谈接触的数据库?这桩场景的数量是巨大的,我们消除了所有的人都被要求的属性是死的简单。

Imagine for example that you are writing a compiler that needs to read attributes from an assembly in order to compile some source code. Do you really want the code in the referenced assembly to be loaded and executed? Do you want to put a requirement on compiler writers that they write compilers that can run arbitrary code in referenced assemblies during the compilation? Code that might crash, or go into infinite loops, or contact databases that the developer doesn't have permission to talk to? The number of awful scenarios is huge and we eliminate all of them by requiring that attributes be dead simple.

这篇关于如果当它们被反射到属性只建造,为什么属性构造如此有限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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