且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#是否可以传递一个类型到一个方法,并让该方法返回该类型的对象?

更新时间:2023-02-14 16:55:44

在你给出的例子,你可能会更好服只是做了以下内容:

  MyClass的VAL =作为myObject的MyClass的; 



不过来回答你的问题 - 是的,答案是使用泛型:

 保护牛逼GetAValue< T>(对象someObject)
{
如果(someObject是T)
{
返回(T)someObject;
}
,否则
{
//我们不能为T可能不为空的
//看到http://***.com/questions/302096/返回null如何灿我回空 - 从-A-仿制方法,在C
返回默认值(T);
}
}

在该方法中T为类型参数。你可以在你的代码完全相同的方式,使用T,你会任何其他类型(例如字符串),但是请注意,在这种情况下,我们并没有放在T是什么任何限制,所以T型仅对象有基本的属性和方法对象的GetType()的ToString()等)



我们必须明确地声明T是什么之前,我们可以使用它 - 例如:

  MyClass的VAL = GetAValue< MyClass的>(myObject的); 
串strVal = GetAValue<串GT;(someObject);

有关详细信息,看一看在的仿制药


MSDN文档

This seems like it would be possible.

protected SameObjectTypeAsInputParameterObjectType GetAValue(someObject,TypeOrReturnObjectYouWant){

//check to see if someObject is null, if not, cast it and send the cast back

}

In your given example you are probably better served just doing the following:

MyClass val = myObject as MyClass;

However to answer your question - yes, the answer is to use generics:

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://***.com/questions/302096/how-can-i-return-null-from-a-generic-method-in-c
        return default(T); 
    }
}

In this method T is a type parameter. You can use T in your code in exactly the same way that you would any other type (for example a string), however note that in this case we haven't placed any restriction on what T is, and so objects of type T only have the properties and methods of the base object (GetType(), ToString() etc...)

We must obviously declare what T is before we can use it - for example:

MyClass val = GetAValue<MyClass>(myObject);
string strVal = GetAValue<string>(someObject);

For more information take a look at the MSDN documentation on Generics