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

相关内容

热门资讯

此事引发广泛关注!智星德州插件... 此事引发广泛关注!智星德州插件最新版本更新内容详解(透视)下载微乐小程序自建房透视(果然是真的辅助教...
备受关注的!wepoker能不... 备受关注的!wepoker能不能透视(透视)微信微乐陕西挖坑小程序下载(切实存在有辅助软件)-哔哩哔...
此事引发广泛关注!hhpoke... 此事引发广泛关注!hhpoker辅助挂(透视)微乐小程序辅助开发(切实是真的辅助教程)-哔哩哔哩hh...
透视肯定!wepoker有辅助... 透视肯定!wepoker有辅助器吗(透视)微乐江西小程序辅助器(果然有辅助神器)-哔哩哔哩1、该软件...
透视攻略!aapoker俱乐部... 透视攻略!aapoker俱乐部靠谱吗(透视)微乐锄大地脚本(一贯是有辅助攻略)-哔哩哔哩1、游戏颠覆...
日前!德州私人局怎么透视(透视... 日前!德州私人局怎么透视(透视)微信微乐挂有没有(竟然有辅助软件)-哔哩哔哩一、德州私人局怎么透视游...
技巧辅助挂!pokemmo手机... 技巧辅助挂!pokemmo手机版脚本免费(透视)微乐春天小程序辅助(竟然是真的辅助神器)-哔哩哔哩1...
透视讲解!wepoker买脚本... 透视讲解!wepoker买脚本靠谱吗(透视)微乐陕西三代自建房挂(真是是真的辅助技巧)-哔哩哔哩1、...
为切实保障!哈糖大菠萝有没有挂... 为切实保障!哈糖大菠萝有没有挂(透视)微乐麻将自建房app(竟然真的有辅助脚本)-哔哩哔哩进入游戏-...
透视数据!wepoker挂(透... 透视数据!wepoker挂(透视)微乐自建房免费黑科技下载(切实存在有辅助方法)-哔哩哔哩1、玩家可...