.NET : How do you get the Type of a null object?

前端 未结 12 1266
暗喜
暗喜 2020-11-28 13:59

I have a method with an out parameter that tries to do a type conversion. Basically:

public void GetParameterValue(out object destination)
{
    object param         


        
12条回答
  •  执念已碎
    2020-11-28 14:43

    @Rally25s:

    string val;
    GetParameterValue("parameterName", out val);
    

    It's unclear from your message (in the answers) what the problem with that one was. If declared as:

    void GetParameterValue(string parameterName, out T val)  { }
    

    Than the call, as you wrote it above, will work (you don't need to specify the type). I'm guess that didn't work for you because you can't use a property as an "out" parameter. The way around that is to use both methods:

    T GetParameterValue(string parameterName, T ununsed)  { }
    

    This would be called like this:

    MyObj.SomeProp = GetParameterValue("parameterName", MyObj.SomeProp);
    

    which is rather kludgey, but not the worse method presented.


    A different method, which I've used in C++, but haven't tried yet in C#, is to have GetParameterValue() some object of you own design, and then implement a number of implicit cast operators for it.

    class ParameterHelper
    {
       private object value;
       public ParameterHelper(object value)   { this.value = value;  }
    
       public static implicit operator int(ParameterHelper v)
         { return (int) v.value; }
    
    }
    ParameterHelper GetParameterValue( string parameterName);
    
    MyObj.SomeProp = GetParameterValue("parameterName");
    

提交回复
热议问题