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

相关内容

热门资讯

透视分享"aapok... 透视分享"aapoker怎么开辅助器"其实是有辅助插件(哔哩哔哩)1、首先打开aapoker怎么开辅...
透视有挂"wpk透视... 透视有挂"wpk透视辅助靠谱吗"切实真的是有辅助器(哔哩哔哩)该软件可以轻松地帮助玩家将wpk透视辅...
透视透视"wpk辅助... 透视透视"wpk辅助"确实是真的辅助方法(哔哩哔哩)1.wpk辅助 选牌创建新账号,点击进入游戏后,...
透视推荐"pokem... 透视推荐"pokemmo修改器手机版"确实存在有辅助技巧(哔哩哔哩)该软件可以轻松地帮助玩家将pok...
透视必备"aapok... 透视必备"aapoker怎么控制牌"其实是有辅助器(哔哩哔哩)1)aapoker怎么控制牌免费钻石:...
透视揭幕"hhpok... 透视揭幕"hhpoker怎么开透视"总是是有辅助技巧(哔哩哔哩)1、下载好hhpoker怎么开透视透...
透视关于"wepok... 透视关于"wepoker开脚本视频"本来真的是有辅助方法(哔哩哔哩)1、wepoker开脚本视频透视...
透视辅助"newpo... 透视辅助"newpoker怎么安装脚本"其实存在有辅助插件(哔哩哔哩)1、这是跨平台的newpoke...
透视解密"hhpok... 透视解密"hhpoker软件安装包"一贯有辅助软件(哔哩哔哩)hhpoker软件安装包能透视中分为三...
透视曝光"hhpok... 透视曝光"hhpoker到底可以作必弊码"本来真的有辅助软件(哔哩哔哩)hhpoker到底可以作必弊...