开发者

Property Type from variable

开发者 https://www.devze.com 2023-02-03 16:27 出处:网络
consider the following class: public class ShortName { public string ValueString { get; set; } private Type ValueType { get; }

consider the following class:

public class ShortName
{
    public string ValueString { get; set; }

    private Type ValueType { get; }

    public typeof(ValueType) Value
    {
        get
        {
            开发者_开发知识库//do stuff
        }
    }
}

This isn't possible as typeof(ValueType) isn't recognized. Can anyone help me define the "Value" property type as the type returned by ValueType?

thanks


This is completely impossible.
If you think carefully about it, it doesn't make any sense in the first place.

Properties must have compile-time types; you're trying to define a property whose type is only known at runtime.
How would you be able to use the property?

Instead, you can either make an object property or use generics.


Not sure what you want but:

public Type Value
{
    get
    {
        return ValueType.GetType();
    }
}

Since typeof(<anything>) will return Type.

If this is not what you want, look into using Generics.


It might be possible using generics. Try:

public class ShortName<T>
{     
     public string ValueString { get; set; }      
     private Type ValueType { get; }      
     public T Value<T>  
     { 
         get {  return /*Something cast to a T */ ; }     
     }
}


public class ShortName<T>
{
    public string ValueString 
    { 
        get 
        {
            return Value.ToString(); // be aware of null ref here!
        }
    }
    private Type ValueType 
    { 
        get 
        {
            return typeof(T);
        }
    }

    public T Value
    {
        get; set;
    }
}
0

精彩评论

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