您的位置:首页 > 其它

NewSlot and ReuseSlot

2011-09-20 21:55 309 查看
namespace CSharpTester
{
class Program
{
static void Main(string[] args)
{
var methodA = typeof(A).GetMethod("Test");
PrintAttributes(typeof(System.Reflection.MethodAttributes), (int)methodA.Attributes);

var methodB = typeof(B).GetMethod("Test");
PrintAttributes(typeof(System.Reflection.MethodAttributes), (int)methodB.Attributes);
}
public static void PrintAttributes(Type attribType, int iAttribValue)
{
if (!attribType.IsEnum) { Console.WriteLine("This type is not an enum."); return; }

FieldInfo[] fields = attribType.GetFields(BindingFlags.Public | BindingFlags.Static);
for (int i = 0; i < fields.Length; i++)
{
int fieldvalue = (Int32)fields[i].GetValue(null);
if ((fieldvalue & iAttribValue) == fieldvalue)
{
Console.WriteLine(fields[i].Name);
}
}
}
}
public interface IA
{
void Test();

void Test1();
}
public class A : IA
{
public void Test() { Console.WriteLine(1); }
void IA.Test1() { Console.WriteLine(1); }
public void Test2() { Console.WriteLine(1); }
public void Test3() { Console.WriteLine(1); }
public void Test4() { Console.WriteLine(1); }
public void Test5() { Console.WriteLine(1); }
}
public class B : IA
{
public void A1() { Console.WriteLine(1); }
public void A2() { Console.WriteLine(1); }
public void A3() { Console.WriteLine(1); }
public void Test() { Console.WriteLine(1); }
public void Test1() { Console.WriteLine(1); }
public void Test2() { Console.WriteLine(1); }
}

}


两个类A,B 继承接口IA,都实现方法Test

以下是运行结果



两个都出现了newslot 和reuseslot,结论是都重用了同样的slot,继承以后所有父类,接口的槽的位置不变

以下是这两个的定义


ReuseSlotIndicates that the method will reuse an existing slot in the vtable. This is the default behavior.

NewSlotIndicates that the method always gets a new slot in the vtable.
url:http://msdn.microsoft.com/en-us/library/system.reflection.methodattributes.aspx

(我的理解就是 有newslot的 说明在当前类型有实现了,否则就在父类或者外部;有reuseslot的就说明该方法必然是重写或者继承自父类,当然方法偏移量应该是要一致的)

如果某个类并没有实现某个方法,而是继承自其父类的实现

那么newslot为false 而reuseslot为true

以下是代码

namespace CSharpTester
{
class Program
{
static void Main(string[] args)
{
var methodA = typeof(A).GetMethod("A1");

PrintAttributes(typeof(System.Reflection.MethodAttributes), (int)methodA.Attributes);
}
public static void PrintAttributes(Type attribType, int iAttribValue)
{
if (!attribType.IsEnum) { Console.WriteLine("This type is not an enum."); return; }

FieldInfo[] fields = attribType.GetFields(BindingFlags.Public | BindingFlags.Static);
for (int i = 0; i < fields.Length; i++)
{
int fieldvalue = (Int32)fields[i].GetValue(null);
if ((fieldvalue & iAttribValue) == fieldvalue)
{
Console.WriteLine(fields[i].Name);
}
}
}
}
public class A : B
{
}
public class B
{
public void A1() { Console.WriteLine(1); }
}
}


以下是运行结果,有ReuseSlot 没有NewSlot



多继承接口的情况下,还需要进一步分析
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐