开发者

C# struct instantiation at runtime

开发者 https://www.devze.com 2023-01-17 07:27 出处:网络
Could anyone provide an example how to create a structure instance at runtime? The structure I\'m using 开发者_StackOverflowdoesn\'t define any constructors, just fields. The GetConstructor() method r

Could anyone provide an example how to create a structure instance at runtime? The structure I'm using 开发者_StackOverflowdoesn't define any constructors, just fields. The GetConstructor() method returns null, and so far I was unable to find a way to achieve this.


Just use Activator.CreateInstance(Type).

Most structs don't actually have a parameterless constructor - there's a different form of IL used (the initobj instruction IIRC).

On the other hand, if a struct doesn't have any constructors, that suggests it's either not very useful or it's mutable - and mutable structs can cause all kinds of problems. If you're in control of the structure code yourself, I'd suggest giving it a constructor and making it immutable. There are probably cases where mutable structs are a necessary evil (particularly around interop) but they're worth avoiding if at all possible.


Have you tried using:

Object o = Activator.CreateInstance(Type t);

...or some of its other overloads?

http://msdn.microsoft.com/en-us/library/system.activator.createinstance%28v=VS.100%29.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消