Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过接口创建假对象_C#_.net_Reflection - Fatal编程技术网

C# 通过接口创建假对象

C# 通过接口创建假对象,c#,.net,reflection,C#,.net,Reflection,我需要通过接口动态创建假对象。这个伪对象的每个方法和属性都应该抛出NotImplementedException。有什么简单的方法可以只使用.NET反射API来实现吗?您可以使用模拟API,例如。它是为单元测试中的模拟而设计的,但它应该满足您的需要。恐怕您唯一的解决方案是使用Reflection.Emit,这并不简单:) 有关更多信息,请参阅或。可能会有所帮助 示例代码(从其主页复制)为: 使用impromptu接口; 使用ImpromptuInterface.Dynamic; 公共接口IMyI

我需要通过接口动态创建假对象。这个伪对象的每个方法和属性都应该抛出NotImplementedException。有什么简单的方法可以只使用.NET反射API来实现吗?

您可以使用模拟API,例如。它是为单元测试中的模拟而设计的,但它应该满足您的需要。

恐怕您唯一的解决方案是使用Reflection.Emit,这并不简单:) 有关更多信息,请参阅或。

可能会有所帮助

示例代码(从其主页复制)为:

使用impromptu接口;
使用ImpromptuInterface.Dynamic;
公共接口IMyInterface{
字符串Prop1{get;}
long Prop2{get;}
Guid Prop3{get;}
布尔Meth1(int x);
}
//匿名类
var anon=新{
Prop1=“测试”,
Prop2=42L,
Prop3=Guid.NewGuid(),
Meth1=Return.Arguments(it=>it>5)
}
IMyInterface myInterface=anon.ActLike();

Castle proxy是一个整洁的库,在运行时为接口生成代理对象。所有主要的模拟框架都在引擎盖下使用Castle代理


学习曲线比使用Moq更陡峭,但它可能更适合您的需要,因为Moq专门用于单元测试,因此API对于您所追求的可能过于“嘈杂”。

您似乎需要使用模拟库。为什么您需要具有NotImplementedException的类?也许有比使用mock更好的解决方案。我有一个带有接口的程序集,文件夹中充满了程序集,其中包含实现这些接口的类。所以在应用程序启动时,我扫描这个文件夹,并将所有接口及其实现注册到Castle IoC容器中。但有一些缺少的实现,所以我需要生成假类,它只会抛出异常,以便在运行时让我知道缺少了一些东西。它是一个非常大的应用程序,所以我不想手动创建这些伪类。Moq(如另一个答案中所建议的)是一个使用反射的库。Emit所以它可能是一个更简单的解决方案!
    using ImpromptuInterface;
    using ImpromptuInterface.Dynamic;

    public interface IMyInterface{

       string Prop1 { get;  }

        long Prop2 { get; }

        Guid Prop3 { get; }

        bool Meth1(int x);
   }

   //Anonymous Class
    var anon = new {
             Prop1 = "Test",
             Prop2 = 42L,
             Prop3 = Guid.NewGuid(),
             Meth1 = Return<bool>.Arguments<int>(it => it > 5)
    }

    IMyInterface myInterface = anon.ActLike<IMyInterface>();