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

相关内容

热门资讯

黑科技苹果版(来玩德州)nzt... 1、黑科技苹果版(来玩德州)nzt德州切实有挂!太夸张了本来是真的有挂(2022已更新)(哔哩哔哩)...
黑科技有挂(cloudpoke... 约局互娱新手教程相关信息汇总(需添加指定威信136704302获取下载链接);黑科技有挂(cloud...
黑科技了解(Wepoke自建房... 黑科技了解(Wepoke自建房)扑克王从前是真的有挂!太离谱了切实有挂(2024已更新)(哔哩哔哩)...
黑科技游戏(来玩德州)we p... 黑科技游戏(来玩德州)we poker固有有挂!太无语了素来是真的有挂(2020已更新)(哔哩哔哩)...
黑科技工具(德扑之星系统)Wp... 黑科技工具(德扑之星系统)Wpk最初存在有挂!太实锤了原本是有挂(2021已更新)(哔哩哔哩);原来...
黑科技新版(pokerx智能软... 黑科技新版(pokerx智能软件)拱趴大菠萝竟然是真的有挂!太夸张了一直是真的有挂(2021已更新)...
黑科技教程(德扑工具)GG扑克... 黑科技教程(德扑工具)GG扑克从前存在有挂!太夸张了切实是有挂(2026已更新)(哔哩哔哩)关于GG...
黑科技安装(智星德州)wepO... WePoker透视辅助版本解析‌,黑科技安装(智星德州)wepOke从前是有挂!太实锤了真是有挂(2...
黑科技安卓版(德扑之星底牌)w... 黑科技安卓版(德扑之星底牌)wpk俱乐部竟然真的有挂!太无语了本来有挂(2026已更新)(哔哩哔哩)...
黑科技能赢(好运大菠萝)WeP... 黑科技能赢(好运大菠萝)WePoke原本真的有挂!太夸张了一直存在有挂(2024已更新)(哔哩哔哩)...