I need to broaden my understanding of how structs are compiled when using generics.
I have the following code, which works
public struct TestStruct
{
public GenericStruct<SecondTestStruct> Header;
public int TestValue;
}
public struct GenericStruct<T>
{
public int MessageSize => System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
}
public struct SecondTestStruct
{
public int TestValue;
}
static void Main(string[] args)
{
TestStruct test = new TestStruct();
Console.WriteLine($"Size of test is: {test.Header.MessageSize}");
}
This prints 'Size of test is: 4'
However, if I change TestStruct to attempt to provide its own size:
public struct TestStruct
{
public GenericStruct<TestStruct> Header;
public int TestValue;
}
I get a runtime error: System.TypeLoadException: Could not load type 'TestStructGenerics.TestStruct' from assembly.
I'm guessing it has to do with the compiler being unable to create the struct compile time. Or perhaps a problem with circular references when handling the generic resolution.
EDIT:
I just realized that I can achieve what I want by changing the second case to:
public struct TestStruct
{
public GenericStruct<TestStruct> Header => new GenericStruct<TestStruct>();
public int TestValue;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…