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

相关内容

热门资讯

透视练习!德州透视插件(HHp... 透视练习!德州透视插件(HHpoker必备)一贯真的有辅助方法(哔哩哔哩)1、点击下载安装,德州透视...
透视课程!哈糖大菠萝怎么挂(透... 透视课程!哈糖大菠萝怎么挂(透视)epoker透视底牌(辅助)真是一直都是有技巧(哔哩哔哩)1、很好...
透视手筋!大菠萝辅助器(WeP... 透视手筋!大菠萝辅助器(WePoKer app)好像存在有辅助软件(哔哩哔哩)1、透视手筋!大菠萝辅...
透视法子!约局吧游戏挂(透视)... 透视法子!约局吧游戏挂(透视)xpoker辅助助手(辅助)总是是有攻略(哔哩哔哩)1、约局吧游戏挂脚...
透视办法!竞技联盟透视插件(A... 透视办法!竞技联盟透视插件(AApoker辅助)果然真的是有辅助攻略(哔哩哔哩)1、实时竞技联盟透视...
透视操作!sohoo开挂辅助(... 透视操作!sohoo开挂辅助(透视)约局吧透视挂下载(辅助)总是一直总是有脚本(哔哩哔哩)约局吧透视...
透视资料!德州局透视脚本(透视... 透视资料!德州局透视脚本(透视)菠萝德普辅助器免费版在哪里(辅助)确实真的是有脚本(哔哩哔哩)该软件...
透视课程!aapoker怎么拿... 透视课程!aapoker怎么拿好牌(HHpoker工具)总是真的是有辅助app(哔哩哔哩)1、点击下...
透视讲义!wejoker辅助器... 透视讲义!wejoker辅助器要钱玩吗(WPK方法)竟然存在有辅助脚本(哔哩哔哩)1、wejoker...
透视经验!hhpkoer辅助挂... 透视经验!hhpkoer辅助挂是真的吗(德普之星透视)其实真的是有辅助方法(哔哩哔哩)在进入hhpk...