【发布时间】:2016-12-26 23:25:21
【问题描述】:
我的应用程序付出了性能损失,因为我使用反射,特别是获取类和属性的属性。
为了优化我的应用程序,我想生成一个基于反射但在运行时替换它的库。
今天我使用类似的东西:
MyAttribute[] attributes = (MyAttribute[])Attribute.GetCustomAttributes(typeof(CurrentNamespace.MyClass), typeof(MyAttribute));
var x = GetX(attributes);
我可以在不同的命名空间中生成具有相同类名的类并静态调用它。
MyReflectingClassInterface reflectingClass = getClassFromAssembly("ReflectingNamespace.MyClass");
var x = reflectingClass.getX(); // can't be static if I want to use interface.
或者, 也许最好的方法是使用一个静态开关:
static public X getX(Type type){
if(type == typeof(CurrentNamespace.MyClass))
return new X(5); // hard coded answer
}
【问题讨论】:
-
您目前是否经常致电
GetCustomAttributes?鉴于它们不会针对给定的类进行更改,您只需为每个类调用一次 - 然后您就可以构建缓存。这可能比生成类要简单得多。 -
您认为为什么会因为使用反射而出现性能问题?确实,它可能会导致它,但你的情况是什么?为什么要使用属性来获取有关您的类的信息?如果仅用于您自己的代码,您可以引入一个枚举(标志)。有很多选择。如果您告诉我们您使用它们的目的,您可能会得到更好的建议。
-
我有我的 REST API 的新旧版本,对于每次调用,我都会检查请求版本,以便知道我是否可以返回新标准,或者我应该保持向后兼容性并返回每个属性名称它的旧标准名称。我将旧名称保留为每个属性的属性。我还根据我作为属性实现的验证规则来验证 REST 输入。
标签: c# optimization reflection