首页 > 开发 > 综合 > 正文

C#学习笔记之四(Attribute, Reflection, Thread, Thread Syn

2024-07-21 02:27:58
字体:
来源:转载
供稿:网友

atributes:
//can add metadata in program, it store with the program
//using ildasm to check atributes

//usage
[codereviewattribute("08/08/2005", "allan zhang",
comment = "that is a attribute test")]
class employee {}

//define target and atr
[attributeusage(attributetargets.class |
attributetargets.constructor |
attributetargets.interface |
attributetargets.method |
attributetargets.field |
attributetargets.property,
allowmultiple=true)]
class codereviewatrribute : system.attribute
{
private string reviewdate;
private string reviewername;
private string reviewcomments;
...
}

reflections: //look the metadata in program, discory, late binding

//display attribute in code
system.reflection.memberinfo inf = typeof(employee);
object[] atributes = inf.getcustomattributes(false);
foreach (object attribute in attributes)
{
codereviewattribute attr = (codereviewattribute) attribute;
console.writeline("this is code was reviewed on {0} by {1} /n comments {2}",
attr.date,
attr.name,
attr.comment )
}

//discovery
assembly asm = assembly.load("mscorlib.dll");
type[] types = asm.gettypes();
foreach(type type in types)
{
console.writeline("type is{0}, type);
console.writeline("/n{0} types found." types.length);
}

//latebinding
type mathtype =type.gettype("system.math");
object obj = activator.createrinstance(mathtype);

type[] parametertypes = new type[2];
parametertypes[0] = type.gettype("system.double");
parametertypes[1] = type.gettype("system.double");
methodinfo powinfo = mathtype.getmethod("pow", parametertypes);

object[] parameters = new object[2];
parameters[0] = 5;
parameters[1] = 3;
object returnvalue = powinfo.invoke(obj, parameters);
console.writeline("5 to the 3rd power is {0}, returnvalue);

thread:
//create implicit threads

using system.threading
thread threadone = new thread(new threadstart(countup));
thread threadtwo = new thread(new threadstart(countup));
threadone.name = "thread one";
threadtwo.name = "thread two";
threadone.start();
threadtwo.start();

//joining & killing threads
//join two threads in current threa
threadone.start();
threadtwo.start();
threadone.join();
threadtwo.join();
//this will print, after two above two threads ends
console.writeline("the other threads done");
//sleep(millisenconds)
threadone.sleep(1);
threadone.abort();

synchronization:
//1. no conflict between threads
interlocked.increment(ref synchvalue);
//2. lock method, this will block other thread when it enter into it
lock(this)
{
int temp = synchvalue;
temp++;
thread.sleep(2);
synchvalue = temp;
synchvalue = temp;
console.writeline("{0} count up: {1}",
thread.currentthread.name,
synchvalue);
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表