gpt4 book ai didi

c# - 最小起订量和参数属性继承

转载 作者:行者123 更新时间:2023-11-30 18:44:44 26 4
gpt4 key购买 nike

当我尝试使用 Moq 模拟类时,方法属性会继承到模拟类,但参数属性不会。

基本上行“let a = (ArgumentsAttribute) p.GetCustomAttributes(typeof (ArgumentsAttribute), true).SingleOrDefault()”不返回属性。运行代码以查看它失败的地方。

如何让这个测试通过?

[TestFixture]
public class MyTests {
[Test]
public void shouldFindAndCallMethodWithAttributes() {
var myInterface = new Mock<MyClass>();
myInterface.Setup(x => x.MyMarkedMethod(1));
myInterface.Setup(x => x.MyMarkedMethod(5));
myInterface.Setup(x => x.MyMarkedMethod(9));

var executor = new MarkedMethodExecutor();
executor.FindAndCallMethodWithAttributes(myInterface.Object);

myInterface.VerifyAll();
}
}

public class MarkedMethodExecutor {
public void FindAndCallMethodWithAttributes(object anObject) {
var methods = from m in anObject.GetType().GetMethods()
where m.GetCustomAttributes(typeof (ExecuteMeAttribute), true).SingleOrDefault() != null
select m;
foreach (var method in methods) {
var callInfos = from p in method.GetParameters()
let a = (ArgumentsAttribute) p.GetCustomAttributes(typeof (ArgumentsAttribute), true).SingleOrDefault()
where a != null
select new {Parameter = p, Attribute = a};
// assume its one argument here for simplicity..
var attribute = callInfos.Single().Attribute;
foreach (var argument in attribute.Arguments) {
method.Invoke(anObject, new[] {argument});
}
}
}
}

public class MyClass {
[ExecuteMe]
public virtual void MyMarkedMethod([Arguments(1, 5, 9)] int arg) {}
}

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ExecuteMeAttribute : Attribute {}

[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public class ArgumentsAttribute : Attribute {
public readonly object[] Arguments;

public ArgumentsAttribute(params object[] arguments) {
Arguments = arguments;
}
}

最佳答案

我不明白你的问题:你想设置属性吗?

您可以使用函数 It.is(match)。也许它有帮助: http://api.moq.me/html/5976987C.htm

关于c# - 最小起订量和参数属性继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2387798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com