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

相关内容

热门资讯

科技通报!hhpoker真的有... 科技通报!hhpoker真的有透视吗(辅助挂)一直有挂(有挂讲解辅助工具);1)辅助插件:进一步探索...
一分钟快速了解!we poke... 一分钟快速了解!we poker插件(辅助挂)原来真的有挂(有挂详情辅助器)1)辅助插件:进一步探索...
免费测试版!wepoker怎么... 免费测试版!wepoker怎么增加运气(辅助挂)总是真的有挂(真的有挂辅助技巧)一、游戏安装教程牌型...
信息共享!wepoker辅助器... 信息共享!wepoker辅助器官方(辅助挂)本来有挂(有挂分享辅助方法)1、许多玩家不知道辅助怎么退...
热点讨论!wepokerplu... 热点讨论!wepokerplus外挂(辅助挂)本来真的有挂(有挂规律辅助攻略)一、可以开透视的定义与...
今日公布!wepoker怎么获... 今日公布!wepoker怎么获得好牌(辅助挂)果然真的是有挂(讲解有挂辅助脚本)脚本下载中分为三种模...
科普常识!德普之星有透视辅助吗... 科普常识!德普之星有透视辅助吗(辅助挂)切实真的是有挂(有挂实锤辅助工具)1、游戏颠覆性的策略玩法,...
推荐十款!wepoker有没有... 推荐十款!wepoker有没有透视方法(辅助挂)一贯真的有挂(讲解有挂辅助攻略)进入游戏-大厅左侧-...
技巧知识分享!拱趴大菠萝万能辅... 技巧知识分享!拱趴大菠萝万能辅助器(辅助挂)本来是有挂(有挂规律辅助软件)1、游戏颠覆性的策略玩法,...
9分钟了解!hhpoker必备... 9分钟了解!hhpoker必备开挂(辅助挂)都是真的有挂(竟然有挂辅助技巧)1、用户打开应用后不用登...