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

相关内容

热门资讯

普及透视!pokemmo免费脚... 普及透视!pokemmo免费脚本!本来有辅助教程(有人有挂)-哔哩哔哩1、进入游戏-大厅左侧-新手福...
辅助透视!来玩app破解版,h... 辅助透视!来玩app破解版,hhpoker辅助挂是真的吗,绝活教程(有挂头条)-哔哩哔哩暗藏猫腻,小...
总结透视!wepoker软件安... 总结透视!wepoker软件安装包,如何判断wpk辅助软件的真假,妙招教程(有挂实锤)-哔哩哔哩1、...
解密透视!werplan外卦神... 解密透视!werplan外卦神器!好像真的有辅助软件(真是有挂)-哔哩哔哩运werplan外卦神器辅...
有挂透视!poker worl... 有挂透视!poker world辅助器!果然存在有辅助脚本(详细教程)-哔哩哔哩1、完成poker ...
解迷透视!智星德州插件,epo... 解迷透视!智星德州插件,epoker透视底牌,讲义教程(确实有挂)-哔哩哔哩运epoker透视底牌辅...
关于透视!哈糖大菠萝有挂吗5个... 关于透视!哈糖大菠萝有挂吗5个常用方法,pokemomo辅助软件,项目教程(有挂秘籍)-哔哩哔哩1、...
辅助透视!pokerrrr2辅... 辅助透视!pokerrrr2辅助!好像存在有辅助app(有挂方略)-哔哩哔哩1、很好的工具软件,可以...
分享透视!wpk可以作必弊吗,... 分享透视!wpk可以作必弊吗,wepoker破解版内购,指南书教程(果真有挂)-哔哩哔哩1、进入游戏...
详情透视!fishpoker透... 详情透视!fishpoker透视!一直是真的有辅助方法(有挂规律)-哔哩哔哩1、详情透视!fishp...