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

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

问题描述

  class GenericClass< T>有没有办法做这样的代码? 
{
void functionA()
{
.A();






$ b

或者,如何调用类型参数(类型是我的自定义类)。

解决方案

要调用泛型类型对象的方法,您必须首先实例化它。 / p>

  public static void RunSnippet()
{
var c = new GenericClass< SomeType>();
}

公共类GenericClass< T>其中T:SomeType,new()
{
public GenericClass(){
(new T())。functionA();



public class SomeType
{
public void functionA()
{
// do something here
Console.WriteLine(我写了这个);
}
}


Is there any way to do code such this:

class GenericClass<T>
{
    void functionA()
    {
        T.A();
    }
}

Or, how to call a function of type parameter (type is some my custom class).

解决方案

To call a method of a generic type object you have to instantiate it first.

public static void RunSnippet()
{
    var c = new GenericClass<SomeType>();
}

public class GenericClass<T> where T : SomeType, new()
{
    public GenericClass(){
        (new T()).functionA();
    }   
}

public class SomeType
{
    public void functionA()
    {
        //do something here
        Console.WriteLine("I wrote this");
    }
}

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

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