简体   繁体   English

通用类和通用方法

[英]generic class and generic methods

class test <T> where T : class
{
    public void Write<T>()
    {
        Console.Write(typeof(T).FullName);
    }
}

In the above class, it is possible to pass in a string for the class ( test<string> Test = new test<string> ) and then int for the method? 在上面的类中,可以为该类传递一个字符串( test<string> Test = new test<string> ),然后为该方法传递int? If so, what is the output? 如果是这样,输出是什么? If not, what problems does this cause? 如果没有,这会导致什么问题? I haven't actually tried this, despite using generics (in my own classes) and generic collections, frequently. 尽管经常使用泛型(在我自己的类中)和泛型集合,但我实际上并未尝试过这样做。

The way I write/see generic classes is as follows: 我编写/查看通用类的方式如下:

class <T> where T : class
{
    public T Write()
    {
        Console.Write(T.ToString());
    }
}

As it was originally written no you cannot. 因为它是最初写的,所以您不能。 In order to use different types at different points in the class, you must have multiple generic parameters. 为了在类的不同位置使用不同的类型,必须具有多个通用参数。 It is possible to define a different one at the method level and get your sample to work 可以在方法级别定义一个不同的样本,并使您的样品工作

class Test<T> where T : class {
  public void Write<U>(U arg1) {
    Console.WriteLine(arg1.ToString());
  }
}

Usage 用法

var t = new Test<string>();
t.Write(42);

As Scott pointed out you can use the same named parameter. 正如Scott指出的,您可以使用相同的命名参数。 Although doing so will cause a warning and generally speaking confuse people. 尽管这样做会引起警告,并且一般来说会使人们感到困惑。 It is much cleaner to have distinct names for all generic parameters currently in scope. 为当前作用域中的所有通用参数使用不同的名称要干净得多。

You'll be wanting to declare a type variable in the method separately to the class - 您将需要在方法中与类分开声明类型变量-

class Test<T> where T : class {

    public void Method<U>(U val) {
        Console.WriteLine(typeof(U).FullName);
    }

}

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

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