创建可以重用的类

创建可以重用的类

本文介绍了创建可以重用的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我想创建可以重用其他类的类。但是当我想访问属性名称,值和类型时,我遇到了问题,我无法做到。请给我一些建议!



例子



Hi everyone!
I want to create class that can reuse for some other class. But I have a problem when I want to access property name, value and type in it I can't do it. please give me some suggest!

Example

public class EmployeeUtility<t>
{
    public void addIndex(T parameter)
    {
       // Here I want to access property name, type, value of ClassA or ClassB

    }
}

public class ClassA
{
    string fullName;
    string lastName;
    public void Index()
    {
      EmployeeUtility<classa> em= new EmployeeUtility<classa>;
      em.addIndex(...);
    }
}
public class ClassB
{
    int     age;
    DateTime born;
    public void Index()
    {
      EmployeeUtility<classb> em= new EmployeeUtility<classb>;
      em.addIndex(...);
    }
}





[edit]已添加代码块 - OriginalGriff [/ edit]



[edit]Code block added - OriginalGriff[/edit]

推荐答案

public class EmployeeUtility<t>
{
    public void addIndex(T parameter)
    {
       Console.WriteLine(parameter.age):
    }
}

public class ClassA
{
    public string fullName {get; set;}
}
public class ClassB
{
    public int age {get; set;}
    public void Index()
    {
      EmployeeUtility<classb> em= new EmployeeUtility<classb>;
      em.addIndex(this);
    }
}
</classb></classb>

你不能这样做,因为在编译时对T类没有限制。所以如果可以的话,如果你这样做会发生什么:

You can't do that because at compile time there is no restriction on what class "T" is going to be. So if you could, what would happen if you did this:

EmployeeUtility<ComboBox> em= new EmployeeUtility<ComboBox>;
em.addIndex(this);

ComboBox类没有age属性,那么会发生什么?你的应用程序会崩溃。



您可以使用 []但即使这样将泛型类型约束为类,它的派生类也只允许您访问基类中的属性,而不是那些添加到派生类中的属性。

The ComboBox class doesn't have an "age" property, so what is going to happen? Your app would crash.

You can restrict what types "T" can be by using Constraints[^] but even then constraining the generic type to a class and it's derivatives only allows you to access the properties in the base class, not those added to derived classes.


这篇关于创建可以重用的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:04