比如class Log()
{
    bool Save=false;
    SaveLog(String Log)
    {
        if (Save)
        { 
            // ...
        }
    }
}class OtherClass()
{
    SaveLog("Log1");
    [DEBUG]
    SaveLog("Log2");
}只有加上[DEBUG]才允许保存日志?

解决方案 »

  1.   

    要求上面这种情况下只输出Log2
      

  2.   

    class LogClass()
    {
        bool Save=false;
        SaveLog(String Log)
        {
            if (Save)
            { 
                // ...
            }
        }
    }class OtherClass()
    {
        new LogClass().SaveLog("Log1");
        [DEBUG]
        new LogClass().SaveLog("Log2");
    }
      

  3.   

    貌似楼主想要实现的效果对同一个方法无法区分
    定义属性类后可以修饰类或者方法
    但是一旦修饰之后类或者方法就确立了这种属性
    比如WebMethod,Serializable一旦被修饰了就拥有了这种属性
    并不能在运行时出现两种差异,楼主的效果还是方法重载才能实现。
      

  4.   

    晕.
    你直接传个参数标识一下不就行了.非要这么麻烦干啥!想自定义(扩展)元数据?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.
     */