日期:2014-05-17  浏览次数:20507 次

关于Attribute和泛型的问题
本帖最后由 KongHuLu 于 2013-08-01 19:20:22 编辑
本来是打算写一个FilterAttribute,挺简单的功能就是判断下验证码

然后因为设计需要,感觉这样写很方便

ValidateCodeAttribute<T> : ActionFilterAttribute where T : ValidateImageBase, new()


本想着没什么问题呢,先写了下面的部分,结果到Attibute杯具了。。Attribute声明部分不能写泛型。。
也就是说不能这样
[ValidateCode<MyValidateImage>]

搜了一下也看到了一些资料说这样设计的原因。。。

现在我想问的就是,大家在遇到这样的场景时是用什么替代方案的呢?

因为自己功底不够扎实,还想问一个比较见笑的问题,MyMethod<ClassA>();这样的语句,那个ClassA本来是通过T传进来的,现在有没有别的方式呢?比如我传入类型的Type,然后通过某种方式写到MyMethod<这个位置>();去执行。觉得是有点别扭,望指导
泛型 Attribute Filter ASP.NET?MVC MVC

------解决方案--------------------
1。可以把type作为参数传进去,比如:
public class ValidateCodeAttribute : Attribute
{
public ValidateCodeAttribute(Type t)
{
}
}

2。这种情况下可以不用泛型,把type作为参数,跟上面一样。如果一定要用泛型,可以反射调用:
MethodInfo method = typeof(xx).GetMethod("MyMethod");
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(new xx(), null);

------解决方案--------------------
引用:
Quote: 引用:

1。可以把type作为参数传进去,比如:
public class ValidateCodeAttribute : Attribute
{
public ValidateCodeAttribute(Type t)
{
}
}

2。这种情况下可以不用泛型,把type作为参数,跟上面一样。如果一定要用泛型,可以反射调用:
MethodInfo method = typeof(xx).GetMethod("MyMethod");
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(new xx(), null);

通过传入Type不能达到这样的  “MyMethod<这个位置>();”是吗?
而且不能用where T : ValidateImageBase, new()?

对的。而且只能反射调用构造函数了。
------解决方案--------------------
先把要做什么讲明白  不然谁都知道你要干嘛
------解决方案--------------------