AutoFixture无法为使用System.ComponentModel.DataAnnotations.RangeAttribute的decimal属性创建对象。
创始人
2024-11-12 14:00:17
0

AutoFixture无法为使用System.ComponentModel.DataAnnotations.RangeAttribute的decimal属性创建对象的问题可以通过自定义AttributeRelay来解决。下面是一个代码示例:

using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using AutoFixture;
using AutoFixture.Kernel;

public class RangeAttributeRelay : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var property = request as PropertyInfo;
        if (property == null)
        {
            return new NoSpecimen();
        }

        var rangeAttribute = property.GetCustomAttribute();
        if (rangeAttribute != null && property.PropertyType == typeof(decimal))
        {
            return context.Resolve(rangeAttribute.Minimum);
        }

        return new NoSpecimen();
    }
}

public class MyClass
{
    [Range(1.0, 10.0)]
    public decimal MyProperty { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var fixture = new Fixture();
        fixture.Customizations.Add(new RangeAttributeRelay());

        var myClass = fixture.Create();

        Console.WriteLine(myClass.MyProperty);
    }
}

上面的代码示例中,我们自定义了一个RangeAttributeRelay类,实现了ISpecimenBuilder接口。在Create方法中,我们通过反射获取属性上的RangeAttribute,并判断属性类型是否为decimal。如果满足条件,我们使用AutoFixture的Resolve方法来生成满足RangeAttribute要求的decimal对象。

在Main方法中,我们首先创建了一个Fixture对象,并添加了自定义的RangeAttributeRelay。然后使用fixture.Create方法来创建MyClass对象,此时AutoFixture就能够正确生成满足RangeAttribute要求的decimal属性对象。

运行上述代码,输出将会是一个满足范围要求的decimal属性值。

相关内容

热门资讯

曝光透视!哈糖大菠萝怎么挂!本... 曝光透视!哈糖大菠萝怎么挂!本来真的有辅助插件(竟然有挂)-哔哩哔哩1、超多福利:超高返利,海量正版...
专业透视!pokerworld... 专业透视!pokerworld破解版下载!真是一直总是有辅助软件(有挂秘诀)-哔哩哔哩1、让任何用户...
解密透视!德州真人透视脚本!果... 解密透视!德州真人透视脚本!果然有辅助app(有挂细节)-哔哩哔哩1、任何德州真人透视脚本透视是真的...
辅助透视!hardrock透视... 辅助透视!hardrock透视工具!其实真的是有辅助脚本(有挂秘笈)-哔哩哔哩1、金币登录送、破产送...
解密透视!pokermaste... 解密透视!pokermaster辅助器!果然真的是有辅助工具(有挂讲解)-哔哩哔哩1、pokerma...
必备透视!拱趴大菠萝有什么挂!... 必备透视!拱趴大菠萝有什么挂!果然真的是有辅助工具(有挂透视)-哔哩哔哩1、首先打开拱趴大菠萝有什么...
推荐透视!约局吧德州透视!确实... 推荐透视!约局吧德州透视!确实一直都是有辅助攻略(的确有挂)-哔哩哔哩1、约局吧德州透视辅助软件下载...
必备透视!拱趴大菠萝有什么挂!... 必备透视!拱趴大菠萝有什么挂!一直一直总是有辅助软件(有挂方式)-哔哩哔哩1)拱趴大菠萝有什么挂辅助...
科普透视!xpoker辅助工具... 科普透视!xpoker辅助工具!一贯是真的有辅助神器(确实有挂)-哔哩哔哩一、xpoker辅助工具游...
科普透视!德州真人透视脚本!本... 科普透视!德州真人透视脚本!本来存在有辅助技巧(有挂攻略)-哔哩哔哩德州真人透视脚本能透视中分为三种...