[英]Passing Generic Object to Method
I want to pass generic(can be of any type) model/class to a method. 我想将泛型(可以是任何类型)模型/类传递给方法。 How to pass that?
如何通过?
if(NewUser)
MethodA(User);
else
MethodA(UserReg);
Let me add some more code : 让我添加更多代码:
private void SetRegionDummy<T>(T obj)
{
foreach (var lookup in obj)
{
// but obj.(obj dot) does not give properties of PcvCompleteViewModel
}
}
//Call this method
SetRegionDummy(this.PcvCompleteViewModel);
[Serializable]
public class PcvCompleteViewModel : StepViewModelBase
{
#region Constructor
#endregion
#region Properties
public List<ChargeVolume> ChargeVolumes { get; set; }
public List<LookUpViewModel> LookUp { get; set; }
public List<ProductViewModel> Products { get; set; }
public List<ProductViewModel> PricingProducts { get; set; }
public List<RegionViewModel> Regions { get; set; }
public decimal ContractYears { get; set; }
public decimal? PropGrowthRate { get; set; }
public decimal? GnicsGrowthRate { get; set; }
}
The method is the same but how to pass a different object model? 方法相同,但是如何传递不同的对象模型?
Both your classes must at least share an interface, or inherit from a common base class, that declares the property you want to be shared among them or else you will not be able to create a method that uses this property. 两个类都必须至少共享一个接口,或从一个公共基类继承,该接口声明要在它们之间共享的属性,否则您将无法创建使用此属性的方法。
In your example, you do not need generics at all. 在您的示例中,您根本不需要泛型。 Assuming your classes are declared this way:
假设您的类是这样声明的:
public class ClassA : IMyInterface {
public IEnumerable<LookUpViewModel> LookUp { get; set; }
public int MyPropertyA { get; set; }
//other properties
}
public class ClassB : IMyInterface {
public IEnumerable<LookUpViewModel> LookUp { get; set; }
public string MyPropertyB { get; set; }
//other properties
}
With a common interface: 具有通用接口:
public interface IMyInterface {
IEnumerable<LookUpViewModel> LookUp { get; set; }
}
You can simply create a method that uses this interface as parameter: 您可以简单地创建一个使用此接口作为参数的方法:
private void SetRegionDummy(IMyInterface obj)
{
foreach (var lookup in obj.LookUp)
{
DoWork(lookup);
}
}
Do you mean this? 你是这个意思吗
public void MyMethod<T>(T genericInput)
{
//do stuff with input
}
If you want to care about the object type, use Generics. 如果要关心对象类型,请使用泛型。
public void MethodA<T>(T obj) {
// do stuff
}
If you don't, just change the parameter type to object
. 否则,只需将参数类型更改为
object
。
public void MethodA(object obj) {
// do stuff
}
Generics in C# can be defined by the calling method when the method signature that looks like the following ( details on MSDN ): 当方法签名如下所示时,可以由调用方法定义C#中的泛型( 有关MSDN的详细信息 ):
public void MyMethod<T>(T viewModel) where T : IEnumerable<IViewModel>
{
}
Note, that you can use the where
syntax to provide type constraints. 注意,可以使用
where
语法提供类型约束。 Then you can invoke this like so: 然后,您可以像这样调用它:
{
var viewModel = GetViewModel();
MyMethod<PcvCompleteViewModel>(viewModel );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.