繁体   English   中英

使用反射获取类构造函数的参数

[英]Get parameter of a class constructor using reflection

我正在为一个类编写单元测试,并且我希望在检查每个参数为null时有单独的异常消息。

我不知道的是如何实现下面的GetParameterNameWithReflection方法:

public class struct SUT
{
    public SUT(object a, object b, object c)
    {
        if (a == null)
        {
            throw new ArgumentNullException(nameof(a));
        }

        // etc. for remaining args

        // actual constructor code
    }    
}

[TextFixture]
public class SutTests
{
    [Test]
    public void constructor_shouldCheckForFirstParameterNull()
    {
        var ex = Assert.Throws<ArgumentNullException>(new Sut(null, new object(), new object()));

        string firstParameterName = GetParameterNameWithReflection(typeof(SUT);)

        Assert.AreEqual(firstParameterName, ex.ParamName);
    }
}

作为奖励,非常欢迎对此类测试的适当性的评论!

怎么样:

static string GetFirstParameterNameWithReflection(Type type)
{
    return type.GetConstructors().Single().GetParameters().First().Name;
}

这断言只有一个构造函数,获取参数,断言至少有一个这样的并返回名称。

此方法将返回第一个构造函数的第一个参数名称。 您可以扩展它以处理多个构造函数和不同的参数。 它使用ParameterInfo类。

    public string GetFirstParameterNameWithReflection(Type t)
    {
        return t.GetConstructors()[0].GetParameters()[0].Name;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM