通用类型参数的调用方法 [英] Call method on parameter of generic type

查看:106
本文介绍了通用类型参数的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个泛型方法,输入有一个通用对象列表。我想在每个列表项上调用一个方法。



我正在做的是写如下内容:

  public void ResetPointProperties< T> (List< T> Points)
{
foreach(T点数)
{
point.Reset();


$ / code $ / pre

如何调用 Reset ()在我的列表项上?

解决方案

然而,缺少的是,现在编译器不知道每个 T 是否具有 reset()方法。因此,您必须将约束添加到 T 参数需要 T 来实现一个接口或从声明这样一个类的类继承 reset()
$ b

例如,让我们假设你有某个地方有以下接口:

  public interface IThing 
{
void reset();
}

然后,你可以声明你的上面的方法如下:

  public void ResetPointProperties< T> (List< T> Points)
其中T:IThing

这强制传递任何类型到 T 类型参数必须实现 IThing 。作为回报,编译器可以保证方法中的 point 实际上有一个可以调用的 reset()方法。

I want to write a generic method that as input has a list of generic objects. I want to call a method on each of the list items.

What I'm trying to do is writing something like:

public void ResetPointProperties<T> (List<T> Points) 
{
    foreach (T point in Points)
    {
       point.Reset();
    }
}

How can I call Reset() on my list items?

解决方案

You are almost there. However, what is missing is that as it stands, the compiler does not know whether/that each T has a reset() method. Therefore, you will have to add a constraint to the T parameter that requires T to implement an interface or inherit from a class that declares such a reset() method.

For instance, let's assume you somewhere have the following interface:

public interface IThing
{
    void reset();
}

Then, you could declare your above method as follows:

public void ResetPointProperties<T> (List<T> Points)
    where T : IThing

This enforces that any type passed to the T type parameter must implement IThing. In return, the compiler can guarantee that point in your method actually has a reset() method that you can invoke.

这篇关于通用类型参数的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆