//Get PropertyDescriptor object for the given property name
var propDesc = TypeDescriptor.GetProperties(typeof(T))[propName];
//Get FillAttributes methodinfo delegate
var methodInfo = propDesc.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic)
.FirstOrDefault(m => m.IsFamily || m.IsPublic && m.Name == "FillAttributes");
//Create Validation attribute
var attribute = new RequiredAttribute();
var attributes= new ValidationAttribute[]{attribute};
//Invoke FillAttribute method
methodInfo.Invoke(propDesc, new object[] { attributes });
Run Code Online (Sandbox Code Playgroud)
您好我正在尝试使用上面的代码在运行时添加Validation属性.但是我得到以下例外:
收集是固定的大小
我正在为我的项目编写命令行界面.用户输入"create project foo",它找到负责"project"的控制器,然后调用该Create
方法,将"foo"作为第一个参数传递.
它在很大程度上依赖于属性和反射:控制器看起来像这样:
[ControllerFor("project")]
class ProjectController
{
[ControllerAction("create")]
public object Create(string projectName) { /* ... */ }
}
Run Code Online (Sandbox Code Playgroud)
我想在解析器的单元测试中使用Moq,如下所示:
Mock<IProjectsController> controller = new Mock<IProjectsController>();
controller.Expect(f => f.Create("foo"));
parser.Register(controller.Object);
parser.Execute("create project foo");
controller.VerifyAll();
Run Code Online (Sandbox Code Playgroud)
将属性添加到接口似乎不起作用 - 它们不是由派生类继承的.
我可以让Moq为被模拟的类添加属性吗?
C#中属性的目的是什么?
我如何知道哪个属性必须用于特定功能?
如何在c#中动态添加它们?
什么是自定义属性?
我正在使用Elmah使用Alex Beletsky的elmah-mvc NuGet包在我的MVC应用程序上记录异常.
应用程序注册了一些全局过滤器,应用于每个被调用的操作
有没有办法阻止在调用Elmah.Mvc.ElmahController
错误日志页面(foo.com/elmah
)时应用某些过滤器?
当然,像下面这样的测试工作,但我正在寻找一种更优雅的方式,不涉及修改过滤器(也不是Elmah/Elmah MVC的源代码).它甚至可能吗?
public class FooAttribute : FilterAttribute, IActionFilter
{
// ...
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.Controller is ElmahController)
{
return;
}
// do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
我知道在运行时无法添加或删除属性.
我想ElmahController
在一个新的包装我可以添加一个排除过滤器,但我不知道如何(如果可能)更改web.config
引用此包装而不是原始控制器.
有谁知道如何以编程方式将[XmlIgnore]
属性添加到c#中的类属性?
我想这样做只有一个类,有一个或两个字段被序列化,因为我需要在运行时.
提前谢谢了.
我有一个我无法修改的现有C#类,但只能使用它.举例:
public class Test {}
Run Code Online (Sandbox Code Playgroud)
我想动态地将属性(MyAttribute)添加到此类Test中,如:
[MyAttribute(TestMode)]
public class Test {}
Run Code Online (Sandbox Code Playgroud)
是否有可能在C#中如何?
注意:当然,我可以从这个Test类派生并以声明方式添加属性,但它意味着创建一个新类,我想避免它.
c# ×5
attributes ×3
.net ×2
asp.net ×1
asp.net-mvc ×1
c#-4.0 ×1
class ×1
elmah ×1
mocking ×1
moq ×1
unit-testing ×1
xml ×1