小新的技术天地

Make It Works !

博客园 首页 新随笔 联系 订阅 管理
6.3.3 字段属性
using System;
using System.Reflection;

namespace FieldAttribs
{
    
public enum RegHives
    
{
        HKEY_CLASS_ROOT,
        HKEY_CURRENT_USER,
        HKEY_LOCAL_MACHINE,
        HKEY_CURRENT_CONFIG
    }

    
    
public class RegKeyAttribute : Attribute
    
{
        
public RegKeyAttribute(RegHives Hive, String ValueName)
        
{
            
this.Hive = Hive;
            
this.ValueName = ValueName;
        }

        
        
protected RegHives hive;
        
public RegHives Hive
        
{
            
get {return hive;}
            
set {hive = value;}
        }

        
        
protected String valueName;
        
        
public String ValueName
        
{
            
get return valueName; }
            
set { valueName = value; }
        }

    }

    
    
class SomeClass
    
{
        [RegKey(RegHives.HKEY_CURRENT_USER, 
"Foo")]
        
public int Foo;
        
        
public int Bar;
    }

    
    
class Test
    
{
        [STAThread]
        
static void Main(string[] args)
        
{
            Type type 
= Type.GetType("FieldAttribs.SomeClass");
            
foreach(FieldInfo field in type.GetFields())
            
{
                
foreach(Attribute attr in field.GetCustomAttributes(true))
                
{
                    RegKeyAttribute rka 
= attr as RegKeyAttribute;
                    
if (null != rka)
                    
{
                        Console.WriteLine(
"{0} will be saved in " + "{1} \\\\ {2}"
                                                        field.Name,
                                                        rka.Hive,
                                                        rka.ValueName);
                    
                    }

                }

            }

        }

    }

}


这个例子跟前一个方法属性的例子类似,就不仔细分析了。
只是注意,与MethodInfo对象从类型对象中获取方法信息一样,FieldInfo对象用于从类型信息中获取字段信息。
PS:
在打代码的时候,总是把field打成filed,以后注意。
输出的时候有两个warning:
warning CS0649 从未对字段“FieldAttribs.SomeClass.Foo”赋值,字段将一直保持其默认值 0
warning CS0649 从未对字段“FieldAttribs.SomeClass.Bar”赋值,字段将一直保持其默认值 0

当然这个例子只是用于演示目的,不用管它
最后执行输出:
Foo will be saved in HKEY_CURRENT_USER \\ Foo
posted on 2004-10-13 11:17  小新0574  阅读(1184)  评论(0编辑  收藏  举报