简体   繁体   English

通用方法将T强制转换为对象类型

[英]Generic method cast T to object type

I have a method that accepts a generic type of BaseViewModel. 我有一个接受BaseViewModel通用类型的方法。 I want to get the actual object in the method. 我想获取方法中的实际对象。

What I tried: 我试过的

public static void LogScreen<T>() where T : BaseViewModel
 {
    var viewModel = T as BaseViewModel;
 }

You are not passing any object into the method, only the parameter type . 您没有将任何对象传递给方法,仅传递了参数type

To apply value correctly, You should use the syntax like: 为了正确地应用价值,您应该使用如下语法:

public static void LogScreen<T>(T TArg)
    where T : BaseViewModel
{
    var viewModel = TArg; //not necessary: as BaseViewModel;
}

In this kind of code You do not really need to use generic and You might go with simplier version as: 在这种代码中,您实际上并不需要使用泛型,并且可以使用以下更简单的版本:

public static void LogScreen(BaseViewModel viewModel)
{
     //already got viewModel as correct type and checked during compile for types
}

Note: The big advantage of using generic approach is putting there some type and then work with the type whole time (great example IEnumerable<int> ). 注意:使用泛型方法的最大优点是将某种类型放入其中,然后一直使用该类型(例如IEnumerable<int>最佳示例)。 If You would do that without generic type, You would need to use object everywhere and You would need to cast the object all the time 如果您在没有泛型类型的情况下执行此操作,则将需要在任何地方使用object ,并且需要始终强制转换对象

  • Generic is advantage there as You can put anything inside. 通用是您的优势,因为您可以在其中放入任何内容。

On the other hand if You have a method, where You have only one type the only one, it is easier to go with strict parameter type (2nd approach). 另一方面,如果您有一个方法,只有一个类型只有一个类型,那么使用严格的参数类型会更容易(第二种方法)。


Comment of ZoharPeled - the code should be written as: ZoharPeled的评论-该代码应编写为:

public static void LogScreen<T>(T TArg)
    where T : BaseViewModel
{
    var viewModel = TArg as BaseViewModel;
    var viewModel2 = TArg;
}

From the compiler's point of view, the type of the reference named viewModel is exactly the same as the type of the reference named viewModel2 - both are BaseViewModel , and both instances may or may not be of any type derived from BaseViewModel . 从编译器的角度来看,名为viewModel的引用的类型与名为viewModel的引用的类型viewModel2 -两者都是BaseViewModel ,并且两个实例可能是也可能不是从BaseViewModel派生的任何类型。 Long story short, the as operator is redundant in this code. 长话短说,此代码中的as运算符是多余的。 Even if you pass an instance of some class derived from BaseModelView you can only reference it as a BaseModelView in this method. 即使您传递了从BaseModelView派生的某个类的实例,您也只能在此方法BaseModelView其作为BaseModelView引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM