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属性值。

相关内容

热门资讯

透视科技!epoker免费透视... 透视科技!epoker免费透视脚本,斗棋联盟bug(果然真的是有挂)1、斗棋联盟bug系统规律教程、...
透视教程!佛手大菠萝辅助,传送... 透视教程!佛手大菠萝辅助,传送屋有没有挂(切实真的是有挂);亲,关键说明,传送屋有没有挂赛季回归,传...
透视辅助!wepoker透视挂... 透视辅助!wepoker透视挂底牌,微乐辅助靠谱麻(好像是真的有挂)1、在微乐辅助靠谱麻ai机器人技...
透视透视!wepoker怎么获... 透视透视!wepoker怎么获得好牌,蜀山四川怎么提高胜率(真是存在有挂)1、蜀山四川怎么提高胜率系...
透视插件!wepoker一直输... 透视插件!wepoker一直输的号能继续打吗,皮皮跑子辅助(竟然有挂)1、皮皮跑子辅助ai辅助优化,...
透视代打!德州圈脚本,微信小程... 透视代打!德州圈脚本,微信小程序多乐辅助下载(好像是真的有挂)透视代打!德州圈脚本,微信小程序多乐辅...
透视脚本!pokerworld... 透视脚本!pokerworld破解版下载,决战卡五星必赢神器(切实是真的有挂)1、用户打开应用后不用...
透视安装!hhpoker辅助挂... 透视安装!hhpoker辅助挂,789大菠萝辅助(一贯是真的有挂);1)789大菠萝辅助辅助挂:进一...
透视了解!wepokerplu... 透视了解!wepokerplus作弊,蘑菇云辅助(一直存在有挂)1、蘑菇云辅助透视辅助简单,蘑菇云辅...
透视游戏!wpk模拟器多开,新... 透视游戏!wpk模拟器多开,新蜜瓜大厅控制器(都是真的是有挂)1、点击下载安装,新蜜瓜大厅控制器插件...