简体   繁体   English

从通用类型创建代理/模拟对象

[英]Creating Proxy/Mock Object From/Of Generic Type

I would like to implement the following method: 我想实现以下方法:

public static T CreateProxyObject<T>(Dictionary<String,Object> setup) 

With the following Rules: 遵循以下规则:

1) I want to stay as generic as possible means T is not known during compile time and I want to be able to return it to user as the mocked/proxy requested type (user can still use normal intellisense to get object's metadata). 1)我想尽可能地保持通用,这意味着T在编译期间是未知的,并且我希望能够将它作为模拟/代理请求的类型返回给用户(用户仍然可以使用常规的intellisense来获取对象的元数据)。

2) It should have all its properties set/setup based on the setup Dictionary: 2)应该根据设置字典来设置/设置其所有属性:

String-> property name of the object

Object-> the return value for this property

Any other method should be implemented with throwing not implemented exception 应该使用抛出未实现的异常的方式来实现任何其他方法

I was trying to use mock of T (from Moq framework) but T must be reference type. 我试图使用T的模拟(来自Moq框架),但是T必须是引用类型。

Had no success as well with Castle DynamicProxy and RealProxy. Castle DynamicProxy和RealProxy也没有成功。

Any Idea? 任何想法?

After searching a bit more I found this answer that guided me to use impromptu-interface which uses expandoobject/dynamic object in order to implement an interface, And together with this answer (which solve the problem of setting the properties dynamically), 搜索了一下经过,我发现这个答案是指导我用即兴的接口 ,它使用expandoobject /动态对象,以实现一个接口,并连同答案(这解决了动态设置属性的问题),

I was able to create the following implementation: 我能够创建以下实现:

public static T CreateProxyObject<T>(Dictionary<String,Object> setup) where T : class
{
   return setup.Aggregate(
          (IDictionary<string, object>) new ExpandoObject(),
            (e, kvSetup) =>
                {
                    e.Add(kvSetup.Key, kvSetup.Value);
                    return e;
                }).ActLike<T>();

 }

That can be used like this: 可以这样使用:

public interface IPerson
{
    string Name { get; set; }
    int Age { get; set; }
    void Method();
}



public class Program
{
    static void Main(string[] args)
    {
       //Dynamic Expando object
        var p = CreateProxyObject<IPerson>(new Dictionary<string, object>
                                       {
                                           {"Name", "a name"},
                                           {"Age", 13}
                                       });
        var n = p.Name;
        var a = p.Age;
        //Throws: 'System.Dynamic.ExpandoObject' does not contain a definition for 'Method'
        p.Method();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM