日期:2014-05-18  浏览次数:20706 次

属性类能不能实现这种功能?
比如
C# code

class Log()
{
    bool Save=false;
    SaveLog(String Log)
    {
        if (Save)
        { 
            // ...
        }
    }
}

class OtherClass()
{
    SaveLog("Log1");
    [DEBUG]
    SaveLog("Log2");
}


只有加上[DEBUG]才允许保存日志?

------解决方案--------------------
没这样玩过,看楼下的

------解决方案--------------------
没产生过这样的想法...
------解决方案--------------------
为什么不给SaveLog为个参数呢
------解决方案--------------------
貌似楼主想要实现的效果对同一个方法无法区分
定义属性类后可以修饰类或者方法
但是一旦修饰之后类或者方法就确立了这种属性
比如WebMethod,Serializable一旦被修饰了就拥有了这种属性
并不能在运行时出现两种差异,楼主的效果还是方法重载才能实现。

------解决方案--------------------
晕.
你直接传个参数标识一下不就行了.非要这么麻烦干啥!

想自定义(扩展)元数据?

C# code
using System;
using System.Reflection;

namespace CustomAttrCS {
    // An enumeration of animals. Start at 1 (0 = uninitialized).
    public enum Animal {
        // Pets.
        Dog = 1,
        Cat,
        Bird,
    }

    // A custom attribute to allow a target to have a pet.
    public class AnimalTypeAttribute : Attribute {
        // The constructor is called when the attribute is set.
        public AnimalTypeAttribute(Animal pet) {
            thePet = pet;
        }

        // Keep a variable internally ...
        protected Animal thePet;

        // .. and show a copy to the outside world.
        public Animal Pet {
            get { return thePet; }
            set { thePet = Pet; }
        }
    }

    // A test class where each method has its own pet.
    class AnimalTypeTestClass {
        [AnimalType(Animal.Dog)]
        public void DogMethod() {}

        [AnimalType(Animal.Cat)]
        public void CatMethod() {}

        [AnimalType(Animal.Bird)]
        public void BirdMethod() {}
    }

    class DemoClass {
        static void Main(string[] args) {
            AnimalTypeTestClass testClass = new AnimalTypeTestClass();
            Type type = testClass.GetType();
            // Iterate through all the methods of the class.
            foreach(MethodInfo mInfo in type.GetMethods()) {
                // Iterate through all the Attributes for each method.
                foreach (Attribute attr in 
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the AnimalType attribute.
                    if (attr.GetType() == typeof(AnimalTypeAttribute))
                        Console.WriteLine(
                            "Method {0} has a pet {1} attribute.", 
                            mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
                }

            }
        }
    }
}

/*
 * Output:
 * Method DogMethod has a pet Dog attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method BirdMethod has a pet Bird attribute.
 */