NewSlot and ReuseSlot
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,繼承以后所有父類,接口的槽的位置不變
以下是這兩個的定義
![]() |
ReuseSlot | Indicates that the method will reuse an existing slot in the vtable. This is the default behavior. |
![]() |
NewSlot | Indicates 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

多繼承接口的情況下,還需要進一步分析

浙公網安備 33010602011771號