Can struct objects be allocated to managed stacks?
Can struct objects be allocated to managed stacks?
-- Yes.
For example, when struct is packed, it is allocated to the managed stack.
For example, let a struct implement an interface.
public interface IReport
{
string Name { get; }
}
public struct Score : IReport
{
public string Name
{
Get {return "80 points from struct ";}
}
}
Another class is used to print the class and method of the interface property value.
public class Tester
{
public void Test(IReport report)
{
Console.WriteLine(report.Name);
}
}
Then the Main method is called as follows:
static void Main(string[] args)
{
var tester = new Tester();
tester.Test(new Score());
Console.ReadKey();
}
Now, we want to check whether struct has been packed.
Open "VS2012 developer command prompt ".
Navigate to the EXE folder and use ildasmto decompile the ilcode to output it to a 1.txt file.
We can see that the struct object is packed.
So how can we avoid packing?
You can add a generic method to the Tester class.
public class Tester
{
public void Test(IReport report)
{
Console.WriteLine(report.Name);
}
public void TestGeneric<T>(T report) where T : IReport
{
Console.WriteLine(report.Name);
}
}
Then use the generic method in the Main method.
static void Main(string[] args)
{
var tester = new Tester();
tester.TestGeneric(new Score());
Console.ReadKey();
}
Run again, decompile again, and view the IL code:
We found that struct is no longer packed.
Why?
The type of method parameters is limited in generic methods, and struct meets the type requirements. When a struct object is passed in as a real parameter, the generic method directly uses struct instead of IReport, thus avoiding struct packing.