How to pass an object value for type values?

I have a type like this:

public class TypeValue
{
    public Type Type { get; private set; }
    public object Value { get; private set; }
}

so I can do something like:

TypeValue tv = ...
int count = (tv.Type) tv.Value;

but the compiler gives me this error:

The type or namespace name 'tv' may not be found (are you not using a directive or assembly reference?)

How do I achieve this?

+3
source share
4 answers

You should just do:

TypeValue tv = ...
int count = (int) tv.Value;

See in the case when you know the type at compile time (in this case you know what countit is int), then there is no point referring to tv.Type. This helps to illustrate why this does not make logical sense and therefore is impossible.

+1
source

. , ? "" - , , . , :

// "typeof" returns a "Type" object.
string foo = (typeof(string))SomeObj;

, .

+3

, , , . ( , ).

,

Type1 obj1 = new Type1();
Type type = typeof(Type1);
Type2 obj2 = (type)obj1;

, . .

public class TypeValue
{
    public Type Type { get; private set; }
    public object Value { get; set; }

    public T GetValueAs<T>()
    {
        if (Value == null)
            return default(T);
        return (T)Value;
    }
}

TypeValue a = new TypeValue();
a.Value = 1;
int b = a.GetValueAs<int>();

public class TypeValue<T>
{
    public Type Type { get { return typeof(T); } }
    public T Value { get; set; }
}

TypeValue<int> a = new TypeValue<int>();
a.Value = 1;
int b = a.Value;
Type c = a.Type;
+3

System.Type System.Object. :

public class TypeValue<T> 
{     
    public T Value { get; private set; } 
} 
+1

Source: https://habr.com/ru/post/1791608/


All Articles