Вопрос

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