通过自定义属性验证或更改方法参数值 [英] validate or change method parameters value in by custom attribute

查看:97
本文介绍了通过自定义属性验证或更改方法参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Friends



是否可以使用自定义属性更改method参数的值?



我想通过自定义属性对Url解码字符串参数,我不想让每个方法都为字符串值写入Url解码代码,我想写一个自定义属性来获取方法参数值并解码它所以我可以为所有方法指定属性,



例如



Hello Friends

Is that possible to change the value of method parameter by using custom attribute?

I want to Url decode string parameter by custom attribute and I don't want to go each and every method to write Url decode code for string value, I want to write one custom attribute to get method parameter value and decode it so I can assign attribute to all methods,

for example

[MyCustomAttribute]
public void MyMethodName(string p1){
}





在MyCustomAttribute类中,参数p1将被解码。如果不可能那么有没有其他方法来完成我的任务而不是在所有方法中执行代码。



谢谢

Imrankhan



In MyCustomAttribute class, the parameter p1 will be decoded. If it is not possible then Is there any other way to accomplish my task instead of doing code in all methods.

Thanks
Imrankhan

推荐答案

如果我明白你在问什么,不。



所有属性都是将公共中间语言(CIL)中的元数据附加到类,方法或其他代码块中;它不会改变代码编译为CIL的方式。此编译的一部分是修改方法名称,添加返回类型以及参数的顺序和类型。例如,

If I understand what you are asking, no.

All attributes do is attach meta data in the Common Intermediate Language (CIL) to a class, method or other block of code; it does not alter how the code is compiled to CIL. A part of this compiling is to "mangle" method names, adding the return type and the order and types of the parameters. For example,
public void MyMethodName(string p1)



可能被编译为类似 _MyMethodName__void_string ,而


might get compiled to something like _MyMethodName__void_string, while

public void MyMethodName(string p1, int p2)
public void MyMethodName(int p1, string p2)



可编译为 _MyMethodName__void_int_string _MyMethodName__void_string_int 。这就是框架如何说明重载和检查参数具有正确类型之间的区别。没有属性可以改变这种行为。



因此,如果你想改变参数类型,就不能使用属性:它们必须在源代码。如果希望 MyMethodName 采用几种不同类型的参数,则必须为每种参数类型创建不同的方法调用。或者,您可以使用类型为 Object 的参数的单个方法,但这意味着必须手动进行类型检查。


might be compiled to _MyMethodName__void_int_string and _MyMethodName__void_string_int. This is how the Framework tells the difference between overloads and checks that parameters have the correct type. No attribute can change this behavior.

So if you want to change the parameter type, you cannot use attributes: they MUST be changed in the source code. If you want MyMethodName to take several different types of parameters, you must create a different method call for each parameter type. Or, you can have a single method with a parameter of type Object, but that would mean having to do your type checking manually.


这篇关于通过自定义属性验证或更改方法参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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