我有C#方法
private static string TypeNameLower(object o)
{
return o.GetType().Name.ToLower();
}
Run Code Online (Sandbox Code Playgroud)
给我输入对象的小写类型名称.
但是如果input是一个设置为null的字符串或者设置为null的nullable int,那么这个方法当然会失败.
在这种情况下如何获取类型名称?
我有一个带out参数的方法,尝试进行类型转换.基本上:
public void GetParameterValue(out object destination)
{
object paramVal = "I want to return this. could be any type, not just string.";
destination = null; // default out param to null
destination = Convert.ChangeType(paramVal, destination.GetType());
}
Run Code Online (Sandbox Code Playgroud)
问题是,通常会有人称之为:
string output;
GetParameterValue(output);
Run Code Online (Sandbox Code Playgroud)
这将失败,因为:
destination.GetType()
Run Code Online (Sandbox Code Playgroud)
destination为null,因此我们无法调用.GetType()它.我们也不能打电话:
typeof(destination)
Run Code Online (Sandbox Code Playgroud)
因为destination是变量名而不是类型名.
那么有没有办法获得设置为null的对象的类型?我认为必须有一种方法可以知道什么类型的存储位置没有分配任何东西.
只是为了提供更多信息,我试图创建一个实用程序方法来获取Oracle存储过程的输出参数.问题是DbParameter.Value对象类型.
对于开发人员来说,最理想的是:
string val = GetParameterValue("parameterName");
Run Code Online (Sandbox Code Playgroud)
值得注意的是,没有类型的铸造.在实践中,你不知道"等于"的lparam,所以我选择了:
string val;
GetParameterValue("parameterName", out val);
Run Code Online (Sandbox Code Playgroud)
在方法中,我会知道输出变量的目标类型.我猜这是一个不好的假设.作为替代方案,我也写了这个方法:
public T GetParameterValue<T>(string paramName)
Run Code Online (Sandbox Code Playgroud)
所以开发人员可以这样做:
string val = GetParameterValue<string>("parameterName");
Run Code Online (Sandbox Code Playgroud)
我发现显式的"字符串"声明是重复的,特别是因为在实践中,目标可能是对象属性和oracle数据类型可能会改变(想想ORM):
MyObj.SomeProp = GetParameterValue<MyObj.SomeProp.GetType()>("parameterName");
Run Code Online (Sandbox Code Playgroud)
但同样,如果MyObj.SomeProp为null,则该.GetType()调用失败.VM必须知道它的类型MyObj.SomeProp …
User x = null;
object o = x;
// determine type with only reference to o
Run Code Online (Sandbox Code Playgroud)
并且泛型不起作用