13,190
社区成员
发帖
与我相关
我的任务
分享
[Author("H. Ackerman", version = 1.1)]
class SampleClass
Author anonymousAuthorObject = new Author("H. Ackerman");
anonymousAuthorObject.version = 1.1;
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // multiuse attribute
]
public class Author : System.Attribute
{
string name;
public double version;
public Author(string name)
{
this.name = name;
version = 1.0; // Default value
}
public string GetName()
{
return name;
}
}
[Author("H. Ackerman")]
private class FirstClass
{
// ...
}
// No Author attribute
private class SecondClass
{
// ...
}
[Author("H. Ackerman"), Author("M. Knott", version = 2.0)]
private class ThirdClass
{
// ...
}
class TestAuthorAttribute
{
static void Main()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
}
private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // reflection
foreach (System.Attribute attr in attrs)
{
if (attr is Author)
{
Author a = (Author)attr;
System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
}
}
}
}
// Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);
// Using Reflection to get information from an Assembly:
System.Reflection.Assembly o = System.Reflection.Assembly.Load("mscorlib.dll");
System.Console.WriteLine(o.GetName());
public static class Singleton
{
public static readonly Singleton Instance = new Singleton();
}
public class Singleton
{
private static Singleton m_instance = null;
private Singleton() { }
public static Singleton getInstance()
{
if(m_instance==null) { m_instance=new Singleton(); }
return m_instance;
}
}
public class Multiton
{
private static Multiton instance1=null;
private static Multiton instance2=null;
private Multiton() { }
public static Multiton getInstance(int whichOne)
{
if(whichOne==1)
{
if(instance1==null) { instance1=new Multiton (); }
return instance1;
}
else
{
if(instance2==null) { instance2=new Multiton (); }
return instance2;
}
}
}