小新的技术天地

Make It Works !

博客园 首页 新随笔 联系 订阅 管理
6.3.1 类属性
通过属性查看远程服务器类型:
using System;
public enum RemoteServers
{
    JEANVALJEAN,
    JAVERT,
    COSETTE    
}

public class RemoteObjectAttribute:Attribute
{
    
public RemoteObjectAttribute(RemoteServers Server)
    
{
        
this.server = Server;
    }

    
protected RemoteServers server;
    
public string Server
    
{
        
get
        
{
            
return RemoteServers.GetName(typeof(RemoteServers),this.server);
        }

    }

}


[RemoteObject(RemoteServers.COSETTE)]
class MyRemotableClass
{
}


class Test
{
    [STAThread]
    
static void Main(string[] args)
    
{
        Type type 
= typeof(MyRemotableClass);
        
foreach(Attribute attr in type.GetCustomAttributes(true))
        
{
            RemoteObjectAttribute  remoteAttr 
= attr as RemoteObjectAttribute;
            
if(null != remoteAttr)
            
{
                Console.WriteLine(
"Create this object on {0}.",remoteAttr.Server);
            }

        }

    }

}


很容易看出,这个程序的输出是:
Create this object on COSETTE.

简单说明一下这里用到的反射
Type type = typeof(MyRemotableClass);
这样type就和MyRemotableClass相关联了。

foreach(Attribute attr in type.GetCustomAttributes(true))

这句话涉及一个问题,GetCustomAttributes方法返回一个Attribute类型的数组。布尔参数表示是否搜索这个成员的继承连,以寻找属性。

RemoteObjectAttribute remoteAttr = attr as RemoteObjectAttribute;
我们用as操作符尝试将当前变量转化为RemoteObjectAttribute类型,如果不能转换,返回null值。(以前一直以为as操作符只是进行类型检查,原来还有类型转换的作用哦,当然还有if语句的作用),所以后面要进行null值检查。
if(null != remoteAttr)
{
    ...
}
posted on 2004-10-12 18:20  小新0574  阅读(974)  评论(0编辑  收藏  举报