在表达式中模拟动态属性,用于 Bogus

Mock dynamic properties in expression, for use with Bogus

我想配置一个 Bogus 规则,在一个简单的模型上设置 dynamic 属性。

N.B. I'm aware this is very much related to the C# compiler/runtime in general and would very much welcome a solution in that context. However, I would also appreciate a Bogus-specific solution, if there is any.

public class Foo
{
    public string Id { get; set; }
    public dynamic Attributes { get; set; }
}

使用假库我想配置一个 Faker 规则,像这样:

public static IReadOnlyCollection<Foo> FakeFoos(int amount)
{
    var config = new Faker<Foo>()
        .StrictMode(false)
        .RuleFor(x => x.Id, y => y.Random.Guid().ToString("N"))
        .RuleFor(x => x.Attributes.......)  // <-- this here
    return config.Generate(amount);
}

假设我想将 foo.Attributes.Percentage 设置为一个整数。我尝试了几种方法,都在 dotnetcore 3.1 上导致了不同的错误。

示例 1:

// Error [CS1963] An expression tree may not contain a dynamic operation
.RuleFor(x => x.Attributes.Percentage, y => y.Random.Int(70, 90))

例二:

// Error System.ArgumentException : Your expression '(x.Attributes As SomeWrappingClass).Percentage' cant be used. 
// Nested accessors like 'o => o.NestedO...
.RuleFor(x => (x.Attributes as SomeWrappingClass).Percentage, y => y.Random.Int(70, 90))

示例 3:

// Error RuntimeBinderException : Cannot perform runtime binding on a null reference
.RuleFor(x => x.Attributes, y => new SomeWrappingClass
{
    Percentage = y.Random.Int(70, 90),
});

有没有人有想法或建议如何在这种情况下设置动态属性

首先,感谢您使用Bogus

使用以下代码:

void Main()
{
   var foo = FakeFoos(1).First();
   foo.Dump();
   Console.WriteLine($"Percentage: {foo.Attributes.Percentage}");
}

选项 1 - 匿名类型

使用 dynamic 最优雅的方法是使用匿名类型:

public static IReadOnlyCollection<Foo> FakeFoos(int amount)
{
   var config = new Faker<Foo>()
       .StrictMode(false)
       .RuleFor(x => x.Id, y => y.Random.Guid().ToString("N"))
       .RuleFor(x => x.Attributes, y => new { Percentage = y.Random.Int(70, 90) });
   return config.Generate(amount);
}


选项 2 - ExpandoObject

更传统地,使用 ExpandoObject:

public static IReadOnlyCollection<Foo> FakeFoos(int amount)
{
   var config = new Faker<Foo>()
       .StrictMode(false)
       .RuleFor(x => x.Id, y => y.Random.Guid().ToString("N"))
       .RuleFor(x => x.Attributes, y =>
            {
               dynamic eo = new ExpandoObject();
               eo.Percentage = y.Random.Int(70, 90);
               return eo;
            });
   return config.Generate(amount);
}


希望对您有所帮助,如果您还有其他问题,请告诉我。 :)