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...
此事引发广泛关注!小唐家乐园辅... 此事引发广泛关注!小唐家乐园辅助器下载链接(辅助)一直有挂辅助工具(有挂细节)-哔哩哔哩1、小唐家乐...
现场直击!pokemmo辅助器... 现场直击!pokemmo辅助器,打哈儿麻将小程序脚本,手段辅助器(证实有挂)-哔哩哔哩1、下载好打哈...
据公告内容!四川途游辅助软件下... 据公告内容!四川途游辅助软件下载(辅助)真是是有辅助工具(真的有挂)-哔哩哔哩1、四川途游辅助软件下...
昨日!大菠萝游戏佛手在线辅助怎... 昨日!大菠萝游戏佛手在线辅助怎么用(辅助)切实真的是有辅助脚本(讲解有挂)-哔哩哔哩1)大菠萝游戏佛...
长期以来!newpoker怎么... 长期以来!newpoker怎么安装脚本,顺欣茶楼开挂,资料辅助软件(有挂透明挂)-哔哩哔哩1、许多玩...
刚刚!菠萝辅助器免费版的功能介... 刚刚!菠萝辅助器免费版的功能介绍(辅助)本来真的是有辅助脚本(有挂秘笈)-哔哩哔哩1、菠萝辅助器免费...
截至目前!约局吧作必弊脚本,微... 截至目前!约局吧作必弊脚本,微信小程序自动透视微乐,法子辅助脚本(有挂透明挂)-哔哩哔哩1、微信小程...
记者获悉!辅助软件购买平台(辅... 记者获悉!辅助软件购买平台(辅助)竟然有挂辅助脚本(讲解有挂)-哔哩哔哩1、玩家可以在辅助软件购买平...
网友热议!哈糖大菠萝辅助器,闲... 网友热议!哈糖大菠萝辅助器,闲逸辅助器,指引辅助工具(有挂透明挂)-哔哩哔哩1、哈糖大菠萝辅助器免费...