Calling new on an interface

本文介绍了一种使用C#编译器的COM互操作特性来通过接口直接创建对象的方法。这种方法允许开发者指定接口的CoClass属性,从而在不直接提及具体类型的情况下实例化对象。

Gieno  Calling new on an interface

Interesting thing: technically there is a way to call new on an interface to create an object. How? Using a feature in the C# compiler for COM-interop support:

using  System.Runtime.InteropServices;
class  Program
{
    
static   void  Main( string [] args)
    {
        IFoo foo 
=   new  IFoo();
    }
}
class  Foo : IFoo
{
}
[ComImport]
[Guid(
" DC1CB768-0BE5-4200-8D0A-C844BFBE3DE7 " )]
[CoClass(
typeof (Foo))]
interface  IFoo
{
}

Here you specify that Foo is a CoClass for the interface IFoo using the three attributes CoClass, ComImport and Guid. It does not matter that no real COM objects are involved, C# compiler is fine with that. What it does, it replaces the call to the IFoo() "constructor" to the equivalent constructor on the co-class Foo.

Interestingly enough, Foo doesn't have to even implement IFoo - the program will compile just fine and it will create an instance of type Foo at runtime, but it will fail when we try to put an object of type Foo into a local variable of type IFoo.

It's yet another way to instantiate a type without mentioning it in source code. As such, it can potentially be a way to achieve what factory methods do - instead of mentioning the concrete type in instantiations all over your code, you can just have a centralized place where you say what type to instantiate. With this you can easily substitute the concrete type via the CoClass attribute.

However, this is not as powerful as factory methods (you have to recompile your app to change concrete class and you can't have multiple concrete types at the same time).

I wouldn't encourage using this stuff anyway because this will probably confuse readers who read your source. But despite of anything, this *is* an interesting technique.

 

转载于:https://www.cnblogs.com/gieno/archive/2009/08/20/1550587.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值