相关疑难解决方法(0)

为什么"十进制"不是有效的属性参数类型?

这真的令人难以置信,但真实.此代码不起作用:

[AttributeUsage(AttributeTargets.Property|AttributeTargets.Field)]
public class Range : Attribute
{
    public decimal Max { get; set; }
    public decimal Min { get; set; }
}

public class Item
{
    [Range(Min=0m,Max=1000m)]  //compile error:'Min' is not a valid named attribute argument because it is not a valid attribute parameter type 
    public decimal Total { get; set; }  
}
Run Code Online (Sandbox Code Playgroud)

虽然这有效:

[AttributeUsage(AttributeTargets.Property|AttributeTargets.Field)]
public class Range : Attribute
{
    public double Max { get; set; }
    public double Min { get; set; }
}

public class Item …
Run Code Online (Sandbox Code Playgroud)

.net c# attributes

129
推荐指数
2
解决办法
3万
查看次数

在xUnit.net中测试参数化类似于NUnit

在xUnit.net框架中是否有类似于NUnit的以下功能?

[Test, TestCaseSource("CurrencySamples")]
public void Format_Currency(decimal value, string expected){}

static object[][] CurrencySamples = new object[][]
{
    new object[]{ 0m, "0,00"},
    new object[]{ 0.0004m, "0,00"},
    new object[]{ 5m, "5,00"},
    new object[]{ 5.1m, "5,10"},
    new object[]{ 5.12m, "5,12"},
    new object[]{ 5.1234m, "5,12"},
    new object[]{ 5.1250m, "5,13"}, // round
    new object[]{ 5.1299m, "5,13"}, // round
}
Run Code Online (Sandbox Code Playgroud)

这将在NUnit GUI中生成8个单独的测试

[TestCase((string)null, Result = "1")]
[TestCase("", Result = "1")]
[TestCase(" ", Result = "1")]
[TestCase("1", Result = "2")]
[TestCase(" 1 ", Result = "2")]
public string …
Run Code Online (Sandbox Code Playgroud)

.net c# nunit unit-testing xunit.net

94
推荐指数
6
解决办法
4万
查看次数

属性构造函数中的Lambda表达式

我创建了一个Attribute名为的类RelatedPropertyAttribute:

[AttributeUsage(AttributeTargets.Property)]
public class RelatedPropertyAttribute: Attribute
{
    public string RelatedProperty { get; private set; }

    public RelatedPropertyAttribute(string relatedProperty)
    {
        RelatedProperty = relatedProperty;
    }
}
Run Code Online (Sandbox Code Playgroud)

我用它来表示类中的相关属性.我将如何使用它的示例:

public class MyClass
{
    public int EmployeeID { get; set; }

    [RelatedProperty("EmployeeID")]
    public int EmployeeNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想使用lambda表达式,以便我可以将强类型传递给我的属性的构造函数,而不是"魔术字符串".这样我可以利用编译器类型检查.例如:

public class MyClass
{
    public int EmployeeID { get; set; }

    [RelatedProperty(x => x.EmployeeID)]
    public int EmployeeNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我以为我可以使用以下内容,但编译器不允许这样做:

public RelatedPropertyAttribute<TProperty>(Expression<Func<MyClass, TProperty>> propertyExpression)
{ ... } …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection attributes custom-attributes

40
推荐指数
5
解决办法
2万
查看次数