C#2.0泛型介绍之简单泛型类。

来源:互联网 发布:祖玛java 7723 编辑:程序博客网 时间:2024/06/05 15:16

下面是一个简单的泛型类。

public class GenericClass<F,T>
    
{
        
private F m_name;
        
private T m_age;
 
        
public GenericClass()
        
{
        }


        
public GenericClass(F name, T age)
        
{
            
this.m_age = age;
            
this.m_name = name;
        }

        
public F Name
        
{
            
get
            
{
                
return this.m_name;
            }

            
set
            
{
                
this.m_name = value;
            }

        }


        
public T Age
        
{
            
get
            
{
                
return this.m_age;
            }

            
set
            
{
                
this.m_age = value;
            }

        }

    }

这是一个最简单的泛型类了。F,T就是就是类型参数。可以是一个对象,也可以是某种数据类型。这样提高了代码的重用性,具体有多少优缺点可以去MSDN上查到,有更权威的解释。
泛型类已经创建好了,下面来调用这个类。

            GenericClass<stringint> gc = new GenericClass<stringint>("Fastyou"20);

            GenericClass
<string, DateTime> gc1 = new GenericClass<string, DateTime>("Fastyou", DateTime.Now);

这里我创建了两个类,用了不同的类型参数。从这里就可以看到泛型的灵活性了。