コード例 #1
0
        public void GenericMethodUsage()
        {
            var      stub    = new StubExample();
            IExample example = stub;

            stub.ImplementGenericMethod <int>(() => 5);
            stub.ImplementGenericMethod <string>(() => "bob");

            Assert.Equal(5, example.GenericMethod <int>());
            Assert.Equal("bob", example.GenericMethod <string>());

            // if no implementation is assigned, default values are used when needed.
            Assert.Equal(default(double), example.GenericMethod <double>());
            Assert.Equal(default(bool), example.GenericMethod <bool>());

            // if you want to make a more complete implementation that works for any generic parameter,
            // put your custom implementation in a decorator and then wrap the stub with that decorator.
            // This DOES require making a custom class, but there's no other way to make a generic-parameterized method:
            // you can't use a lambda or pass in a delegate.
        }