创建可以重用的类 [英] Create class that can reuse

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

问题描述

大家好!

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



例子



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]

推荐答案

首先,整理你的角色案例:C#区分大小写,所以 ClassA classa - 我猜这是一个减少的例子,你没有尝试编译,而不是你试图使用的真实例子,但你仍然必须准确或人们会回答错误的问题并忽略你的真实问题!



其次,你不能在基于类的泛型方法中访问特定于类的值。你传入的方法 - 因为系统不知道它会是什么类。

你说你想这样做:

Firstly, sort out your character case: C# is case sensitive, so ClassA is not the same as classa - I'm guessing this is a "cut down" example that you didn't try to compile, rather than a "real example" you are trying to work with but you still have to be accurate or people will answer the wrong problem and ignore your real one!

Secondly, you can't access class specific values in a generic method based on the class of the method you are passing in - because the system doesn't know what class it will be.
You are saying you want to do this:
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.


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

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