public static void RepeatedAssertion( IMyInterface fake, Exception exception) { "establish" .x(() => { fake = A.Fake<IMyInterface>(o => o.Strict()); ////fake = A.Fake<IMyInterface>(); A.CallTo(() => fake.DoIt(Guid.Empty)).Invokes(() => { }); fake.DoIt(Guid.Empty); fake.DoIt(Guid.Empty); }); "when asserting must have happened when did not happen" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.DoIt(Guid.Empty)).MustHaveHappened(Repeated.Exactly.Once))); "it should throw an expectation exception" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "it should have an exception message containing the name of the method" .x(() => exception.Message.Should().Contain("DoIt")); }
public AccesByInterfaceMethodBehavior() : base() { var myClass = new ImplementsInterface(); this.myInterface = myClass as IMyInterface; this.timer = new TimeSpan(); }
public async Task MyMethod( IMyInterface dependency, CancellationToken cancellationToken) { await dependency.MyAsyncOperation(); await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); }
/// <summary> /// Allows calling the <see cref="IMyInterface.MyInterfaceMethod"/> method against the null reference. /// </summary> /// <param name="myInterface">An instance of the <see cref="IMyInterface"/>.</param> /// <exception cref="ArgumentNullException"> - it the <paramref name="myInterface"/> is null.</exception> public static void ProtectedMyInterfaceMethodCall(this IMyInterface myInterface) { if (myInterface == null) { throw new ArgumentNullException($"{nameof(myInterface)} cannot be null."); } myInterface.MyInterfaceMethod(); }
public async Task MyMethod( IMyInterface dependency, CancellationToken cancellationToken) { await dependency.MyAsyncOperation(); await dependency.MyAsyncOperation(cancellationToken); }
public void DemonstrateJustMockJustCodeIntegration() { IMyInterface myInterfaceMock = Mock.Create <IMyInterface>(); myInterfaceMock.Arrange(x => x.Everywhere(Arg.AnyString, Arg.AnyInt, Arg.AnyInt)).Returns(0M); myInterfaceMock.Arrange(x => x.Here(Arg.AnyString, Arg.AnyGuid)).Returns(false); myInterfaceMock.Arrange(x => x.There(Arg.AnyString, Arg.IsAny <System.DateTime>())).Returns(""); }
public static void RunTest() { IMyInterface myObj = Core.CreateImplementedInstance <IMyInterface, WrapperInterface>(); myObj.TheInt = 123; Assert.Equal("The resulting string is: blabla_123", myObj.GetResultingStr("blabla", 123)); }
public static void Main() { var services = new ServiceCollection() .AddSingleton <IMyInterface, MyImplementation>() .BuildServiceProvider(); IMyInterface impl = services.GetRequiredService <IMyInterface>(); impl.DoSomething(); }
public void MethodParamNamesAreReplicated() { // Try with interface proxy (with target) IMyInterface i = generator.CreateInterfaceProxyWithTarget(typeof(IMyInterface), new MyClass(), new StandardInterceptor()) as IMyInterface; ParameterInfo[] methodParams = GetMyTestMethodParams(i.GetType()); Assert.AreEqual("myParam", methodParams[0].Name); }
public async Task MyMethod( IMyInterface dependency, string value, CancellationToken cancellationToken) { await dependency.MyAsyncOperation(value); await dependency.MyAsyncOperation(value, cancellationToken); }
public static void Main() { Type myNestedClassType = CreateCallee(Thread.GetDomain()); // Cretae an instance of 'MyNestedClass'. IMyInterface myInterface = (IMyInterface)Activator.CreateInstance(myNestedClassType); Console.WriteLine(myInterface.HelloMethod("Bill")); }
public async Task MyMethod( IMyInterface dependency) { var cancellationToken = CancellationToken.None; await dependency.MyAsyncOperation(); await dependency.MyAsyncOperation(cancellationToken); }
/* * 10.3、接口的实现 * 接口的定义: * interface IMyInterface * { * ...... * } * 接口应注意的细节: * 1.不允许使用访问修饰符(public、private、protected或internal)所有接口成员都是隐式公共的。 * 2.接口成员不能包含代码体。 * 3.接口不能定义字段成员。 * 4.不能用关键字static、virtual、abstract或sealed来定义接口成员。 * 5.类型定义成员是禁止的。 * 6.要隐藏基接口中继承的成员,可以用关键字new来定义它们。 * interface IMyBaseInterface * { * void DoSomething(); * } * * interface IMyInterface : IMyBaseInterface * { * new void DoSomething(); * } * 7.在接口中定义的属性可以定义访问块get和set。 * interface IMyInterface * { * int MyInt{ get; set; } * } * 接口不能指定应如何存储属性数据,因为接口不能指定字段。 * 8.接口与类一样,可以定义为类的成员,但是不能定义为其它接口的成员,因为接口不能包含类型定义。 * * 在类中实现接口: * public interface IMyInterface * { * void DoSomething(); * void DoSomethingElse(); * } * public class MyClass : IMyInterface * { * public void DoSomething(){} * public void DoSomethingElse(){} * } * 实现接口应注意的细节: * 1.实现接口的类必须包含该接口所有成员的实现代码,且必须匹配指定的签名,并且必须是公共的。 * 2.可使用关键字virtual或abstract来实现接口成员,但不能使用static或const。 * 3.可以在基类上实现接口成员,而子类在实现接口时不需要实现。 * public interface IMyInterface * { * void DoSomething(); * void DoSomethingElse(); * } * public class MyBaseClass * { * public void DoSomething(){} * } * public class MyClass : MyBaseClass,IMyInterface * { * public void DoSomethingElse(){} * } * 4.继承一个实现给定接口的基类,就意味着派生类隐式地支持这个接口。 * 5.public class MyClass : IMyInterface * { * void IMyInterface.DoSomething(){} //显式实现接口成员 * public void DoSomethingElse(){} //隐式实现接口成员 * } * 只有隐式实现可以直接通过MyClass的对象实例来访问。 * MyClass myObj = new MyClass(); * myObj.DoSomethingElse(); * IMyInterface myInt = myObj; * myInt.DoSomething(); * myInt.DoSomethingElse(); * * 其他属性存取器: * 如果实现带属性的接口,就必须实现匹配的get/set存取器,这并不是绝对正确的。 * 如果在定义属性的接口中只包含set块,就可给类中的属性添加get块,反之亦然。但只有隐式实现接口时才能这么做。 * * */ static void Main(string[] args) { MyClass myObj = new MyClass(); IMyInterface myInt = myObj; myObj.DoSomethingElse(); myInt.DoSomething(); myInt.DoSomethingElse(); ReadKey(); }
public static void Main(string[] args) { InterfaceTest it = new InterfaceTest(); it.IMethod(); IMyInterface imc = it; imc.IMethod(); }
public void TestMethod() { IMyInterface objectToTest = GetObjectToTest(); //Do your generic test of all implementations of IMyInterface objectToTest.Setup(); //... Assert.Equal(objectToTest.Property, 100); //etc }
public static void CustomInterfaceConverter_Deserialization() { string json = "\"myString\""; IMyInterface result = JsonSerializer.Deserialize <IMyInterface>(json); Assert.IsType <MyClass>(result); Assert.Equal("myString", result.StringValue); Assert.Equal(42, result.IntValue); }
public void AnotherMethod() { //get the current page and cast it to the interface IMyInterface page = this.Page as IMyInterface; // now I can call the methods of the interface if (page != null) { page.SomeMethod(); } }
public Form2(IMyInterface frm) { InitializeComponent(); cbSbit.DataSource = Enum.GetValues(typeof(StopBits)); cbSbit.SelectedIndex = 1; cbP.DataSource = Enum.GetValues(typeof(Parity)); cbP.SelectedIndex = 0; cbBaud.SelectedIndex = 3; this.frm = frm; cbPort.DataSource = SerialPort.GetPortNames(); }
static void Main(string[] args) { ITypeConfig typeConfig = Core.FindOrCreateTypeConfig <IMyInterface, WrapperInterface>("MyGeneratedClass"); typeConfig.SetPropBuilder(DelegatePropBuilder.TheDelegatePropBuilder, nameof(IMyInterface.TheStr)); typeConfig.ConfigurationCompleted(); IMyInterface myObj = Core.GetInstanceOfGeneratedType <IMyInterface>(); }
public async Task MyMethod( IMyInterface dependency, int value1, int value2, string value3, CancellationToken cancellationToken) { await dependency.MyAsyncOperation(value3 : value3, value1 : value1, value2 : value2); await dependency.MyAsyncOperation(value1, cancellationToken : cancellationToken); }
public ProxyClass() { if (IsVs2014()) { impl = new Vs2014Impl(); } else { impl = new Vs2013Impl(); } }
/// <summary> /// <para>Метод класса и Интерфейсный метод имеют разные записи в таблице методов</para> /// <para>И указывают на РАЗНЫЕ реализации</para> /// </summary> private static void Example2() { var m2 = new MyClass2(); m2.MyMethod(); // output: MyClass2 implementation of IMyInterface IMyInterface i2 = m2; i2.MyMethod(); // output: MyClass2 EXPLICIT implementation of IMyInterface }
public static void RunTest() { IMyInterface myInterfaceObj = Core.CreateImplementedInstance <IMyInterface, WrapperInterface>(); myInterfaceObj.TheInt = 1234; myInterfaceObj.TheStr = "Hello"; string str = myInterfaceObj.GetResultingStr("blabla", 123); Core.Save("GeneratedCode"); Assert.Equal("The resulting string is: blabla_1234", str); }
/// <summary> /// Метод класса и Интерфейсный метод имеют разные записи в таблице методов, но указывают на одну реализацию /// </summary> private static void Example1() { var m1 = new MyClass1(); m1.MyMethod(); // output: MyClass1 implementation of IMyInterface IMyInterface i1 = m1; i1.MyMethod(); // output: MyClass1 implementation of IMyInterface }
static void Main(string[] args) { // 這裡將會建立 DI 容器 IUnityContainer container = new UnityContainer(); // 進行抽象型別與具體實作類別的註冊 container.RegisterType <IMyInterface, DefaultClass>(); container.RegisterType <IMyInterface, NewClass>("New"); // ConsoleMessage 類別內有 4 個建構式 // 使用 InjectionConstructor 指定使用哪個建構式 container.RegisterType <IMessage, ConsoleMessage>( new InjectionConstructor("Vulcan", 50, typeof(IMyInterface)), new InjectionProperty("Cost", 999.168), new InjectionMethod("Init", typeof(IMyInterface), "原始方法注入的訊息文字") ); #region 手動解析出一個物件,並且該物件作為其他要注入物件需要注入的參考物件 // 進行抽象型別的具體實作物件的解析 IMyInterface newClass = container.Resolve <IMyInterface>("New"); IMessage messageResolveOverride = container.Resolve <IMessage>( new ParameterOverride("name", "Will"), new ParameterOverride("age", 99), new ParameterOverride("myInterface", newClass), new PropertyOverride("Cost", 168.123)); // 執行取得物件的方法 messageResolveOverride.Write("Hi Vulcan"); Console.WriteLine("Press any key for continuing..."); Console.ReadKey(); #endregion #region 使用 typeof 來指定要覆寫注入具體實作物件 (搭配 DependencyOverride ,就無需一一指定) // 進行抽象型別的具體實作物件的解析 IMessage messageResolveOverride2 = container.Resolve <IMessage>( new ParameterOverride("name", "Will"), new ParameterOverride("age", 99), new ParameterOverride("myInterface", typeof(NewClass)), // 1. 請將上面這行程式碼註解,並且解除底下這行註解,看看執行結果有何不同 // 2. 請將上面與下面那一行程式碼都註解起來,看看執行結果有何不同 //new DependencyOverride<IMyInterface>(typeof(NewClass)), new PropertyOverride("Cost", 168.123)); messageResolveOverride2.Write("Hi Vulcan"); Console.WriteLine("Press any key for continuing..."); Console.ReadKey(); #endregion }
static void Main(string[] args) { MyClass myClass = new MyClass(); myClass.DoSomething(); myClass.DoElse(); IMyInterface myInterface = myClass; myInterface.DoElse();//this must be called with interface myInterface.DoSomething(); Console.ReadKey(); }
static void InterfaceAssignment() { // <InterfaceDeclaration> MyClass myClass = new MyClass(); // Declare and assign using an existing value. IMyInterface myInterface = myClass; // Or create and assign a value in a single statement. IMyInterface myInterface2 = new MyClass(); // </InterfaceDeclaration> }
public void ProxyForClassWhichImplementsInterfaces() { object proxy = _generator.CreateClassProxy( typeof(MyInterfaceImpl), new ResultModifiedInvocationHandler( )); Assert.IsNotNull(proxy); Assert.IsTrue(typeof(MyInterfaceImpl).IsAssignableFrom(proxy.GetType())); Assert.IsTrue(typeof(IMyInterface).IsAssignableFrom(proxy.GetType())); IMyInterface inter = (IMyInterface)proxy; Assert.AreEqual(44, inter.Calc(20, 25)); }
public void can_get_an_expando_object_to_act_as_an_interface() { dynamic expando = Build <ExpandoObject> .NewObject( Prop1 : "Test", Prop2 : 42L, Prop3 : Guid.NewGuid(), Meth1 : Return <bool> .Arguments <int>(it => it > 5) ); IMyInterface myInterface = Impromptu.ActLike(expando); Assert.Equal("Test", myInterface.Prop1); Assert.Equal(true, myInterface.Meth1(10)); }
public void GenericMethodWithOutDecimalParameter() { IMyInterface mock = MockRepository.Mock <IMyInterface>(); decimal expectedOutParameter = 1.234M; //decimal emptyOutParameter; mock.Expect(x => x.GenericMethod(out Arg <decimal> .Out(expectedOutParameter).Dummy)); decimal outParameter; mock.GenericMethod(out outParameter); Assert.Equal(expectedOutParameter, outParameter); }
static void EntryPoint(IMyInterface interfaceRef) { MyClass1 class1 = (MyClass1)interfaceRef; // Noncompliant int privateData = class1.Data; class1 = interfaceRef as MyClass1; // Noncompliant if (class1 != null) { // ... } var interf = (IMyInterface2)interfaceRef; interf = (IMyInterface2)class1; var o = (object)interfaceRef; }
public LoggerDecorator(IMyInterface myInterface, ILog myLog) { if (myInterface == null) { throw new ArgumentNullException("IMyInterface is null"); } _MyInterface = myInterface; if (myLog == null) { throw new ArgumentNullException("ILog instance is null"); } _MyLog = myLog; // This is change 1. _MyInterface.SomeEvent += _MyInterface_SomeEvent; }
static void EntryPoint(IMyInterface interfaceRef) { MyClass1 class1 = (MyClass1)interfaceRef; // Noncompliant int privateData = class1.Data; class1 = interfaceRef as MyClass1; // Noncompliant if (class1 != null) { // ... } var interf = (IMyInterface2)interfaceRef; interf = (IMyInterface2)class1; var o = (object)interfaceRef; }
static void EntryPoint(IMyInterface interfaceRef) { MyClass1 class1 = (MyClass1)interfaceRef; // Noncompliant {{Remove this cast and edit the interface to add the missing functionality.}} // ^^^^^^^^^^^^^^^^^^^^^^ int privateData = class1.Data; class1 = interfaceRef as MyClass1; // Noncompliant // ^^^^^^^^^^^^^^^^^^^^^^^^ if (class1 != null) { // ... } var interf = (IMyInterface2)interfaceRef; interf = (IMyInterface2)class1; var o = (object)interfaceRef; }
void bTemp(IMyInterface imi) { Person p = imi as Person; p.Name = "Hata " + this.name; }
public ClassC(IMyInterface implement) { _implement = implement; }
public MyDecorator(IMyInterface decoratedObject, DepA depA) { DecoratedObject = Argument.NotNull(nameof(decoratedObject), decoratedObject); DepA = Argument.NotNull(nameof(depA), depA); }
public ComplexObject() { id = n++; Desc = "#" + id; data = new InternalData { X = 2 * id, Y = 3 * id * (isEven ? 1 : -1), IsNeg = ! isEven, Desc = (id %3==0 ? null: "_"+Desc+"_") }; structData = new StructData(); switch (id % 3) { case 0: structData.myFlags = Flags._False_; break; case 1: structData.myFlags = Flags._True_; break; default: structData.myFlags = Flags._FileNotFound_; break; } var r = id % 255; var g = (id + 1) % 255; var b = (id + 2) % 255; color = Color.FromArgb(r, g, b); isEven = (id % 2 == 0); value = 4 * id; date = new DateTime(2015, 12, 18).AddDays(id); time = TimeSpan.Zero.Add(TimeSpan.FromSeconds(id)); SomeStrings = new string[id%32]; someInts = new int[id % 32]; someDoubles = new double[id % 32]; for(int i=0; i < id % 32; i++) { int n = (id + i); SomeStrings[i] = n.ToString("X"); someInts[i] = n; someDoubles[i] = 2 * (n + i); } myInterface = id % 2 == 0 ? new MyInterfaceImpl_V1() : new MyInterfaceImpl_V2(); aFieldWithAbstractType = new AnAbstractTypeImpl(); }
public MyDomainService(IMyInterface myInterface) { _myInterface = myInterface; }
public Complex(string s, decimal d, IMyInterface instance, AbstractClass abstractClass) { Instance = instance; AbstractClass = abstractClass; }
public DecoratorExampleProxy(IMyInterface target, MyDecorator decorator) { this.target = target; this.decorator = decorator; }
public void RemoveCallback() { _myInterface = null; }
public MyClass(IMyInterface mi) { this.d = mi; }
public SampleController(IMyInterface service) { _service = service; }
public void AddCallback(IMyInterface myInterface) { _myInterface = myInterface; }
public MyDependencyClass(IMyInterface mi) { }
public MyWindsorClass(IMyInterface obj) { this.Dep = obj; }
public int InvokeCall(IMyInterface mc, double d) { return mc.InterfaceMethod(d); }