Csharp/C Sharp/Generics/Generic Class Hierarchy — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 11:45, 26 мая 2010
Содержание
A derived class with its own type parameters
using System;
class MyClass<T> {
T ob;
public MyClass(T o) {
ob = o;
}
public T getob() {
return ob;
}
}
class ClassA<T, V> : MyClass<T> {
V ob2;
public ClassA(T o, V o2) : base(o) {
ob2 = o2;
}
public V getob2() {
return ob2;
}
}
class Test {
public static void Main() {
ClassA<string, int> x = new ClassA<string, int>("Value is: ", 9);
Console.Write(x.getob());
Console.WriteLine(x.getob2());
}
}
A non-generic class can be the base class of a generic derived class
using System;
class MyBaseClass {
int num;
public MyBaseClass(int i) {
num = i;
}
public int getnum() {
return num;
}
}
class MyGenericClass<T> : MyBaseClass {
T ob;
public MyGenericClass(T o, int i) : base (i) {
ob = o;
}
public T getob() {
return ob;
}
}
class HierDemo3 {
public static void Main() {
MyGenericClass<String> w = new MyGenericClass<String>("Hello", 7);
Console.WriteLine(w.getob());
Console.WriteLine(w.getnum());
}
}
A simple generic class hierarchy
using System;
class GenericClass<T> {
T myObject;
public GenericClass(T o) {
myObject = o;
}
public T getmyObject() {
return myObject;
}
}
class GenericClass2<T> : GenericClass<T> {
public GenericClass2(T o) : base(o) {
}
}
class Test {
public static void Main() {
GenericClass2<string> g2 = new GenericClass2<string>("www.nfex.ru");
Console.WriteLine(g2.getmyObject());
}
}
Overriding a virtual method in a generic class
using System;
class MyBaseGenericClass<T> {
protected T myObject;
public MyBaseGenericClass(T o) {
myObject = o;
}
public virtual T getmyObject() {
Console.Write("Base"s getmyObject(): " );
return myObject;
}
}
class MyGenericClass<T> : MyBaseGenericClass<T> {
public MyGenericClass(T o) : base(o) { }
public override T getmyObject() {
Console.Write("overide getmyObject(): ");
return myObject;
}
}
class Test {
public static void Main() {
MyBaseGenericClass<int> myObject = new MyBaseGenericClass<int>(8);
Console.WriteLine(myObject.getmyObject());
myObject = new MyGenericClass<int>(9);
Console.WriteLine(myObject.getmyObject());
}
}
The overriding method cannot change the inherited constraints.
using System;
public class MyClass {
public virtual void MethodA<T>(T arg)
where T : new() {
}
}
public class YClass : MyClass {
public override void MethodA<T>(T arg) {
T obj = new T();
}
}