这似乎是可能的.
protected SameObjectTypeAsInputParameterObjectType GetAValue(someObject,TypeOrReturnObjectYouWant){
//check to see if someObject is null, if not, cast it and send the cast back
}
Run Code Online (Sandbox Code Playgroud)
Jus*_*tin 11
在您给出的示例中,您可能更好地执行以下操作:
MyClass val = myObject as MyClass;
Run Code Online (Sandbox Code Playgroud)
但是要回答你的问题 - 是的,答案是使用泛型:
protected T GetAValue<T>(object someObject)
{
if (someObject is T)
{
return (T)someObject;
}
else
{
// We cannot return null as T may not be nullable
// see http://stackoverflow.com/questions/302096/how-can-i-return-null-from-a-generic-method-in-c
return default(T);
}
}
Run Code Online (Sandbox Code Playgroud)
在该方法中,T是类型参数.您可以在代码中使用与任何其他类型(例如字符串)完全相同的方式,但请注意,在这种情况下,我们没有对T是什么进行任何限制,因此仅对类型T的对象具有基座的属性和方法object
(GetType()
,ToString()
等...)
在我们使用它之前,我们必须明确声明T是什么 - 例如:
MyClass val = GetAValue<MyClass>(myObject);
string strVal = GetAValue<string>(someObject);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看有关Generics的MSDN文档
这似乎会更好地内联.
你能做的是:
var requestedObject = someObject as TheTypeYouWant;
Run Code Online (Sandbox Code Playgroud)
当您声明类似的内容时,您将不会获得空引用异常.然后你可以做一个简单的事情
if(requestedObject != null){
...
}
Run Code Online (Sandbox Code Playgroud)