문제

I'm trying to create a class from its name held in a string. I've tried a bunch of things but always get "Value cannot be null"

Here's the class

public static readonly MigraDoc.DocumentObjectModel.Color Aquamarine
Member of MigraDoc.DocumentObjectModel.Colors

AquaMarine is a class held in MigraDoc.DocumentObjectModel.Colors and is a class of Color

Here's what I tried which is as close as what I thought should work:

Color myColor = (Color)Activator.CreateInstance(Type.GetType("MigraDoc.DocumentObjectModel.Colors+SlateBlue")); 
//+ for nested classes

A variant:

Color myColor = (Color)Activator.CreateInstance(Type.GetType("MigraDoc.DocumentObjectModel+Colors+SlateBlue"));

But I always get:

Value cannot be null.
Parameter name: type

I feel like the solution should not be very far... Any ideas ? :)

도움이 되었습니까?

해결책

No, Aquamarine is not a class, it's a variable. You can't create an instance of a variable...

다른 팁

You get the null parameter exception because Type.GetType() returns null. What you specified as argument for Type.GetType() is a Field name, not a type name. The type name would be "MigraDoc.DocumentObjectModel.Color".

If you want the field named SlateBlue from that type, you would need to use GetField() on the type that contains the colors.

I think you are confusing type (class/struct) and instance here. Aquamarine contains an instance of the type Color. That is not the same as the type itself.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top