动态调用<T>对象类

时间:2019-12-19 14:44:06

标签: c# .net entity-framework

如何动态通过课程? (编辑) 用名称字符串=(

我想将A1或A2传递给getData函数

有什么想法或建议可以支持我吗?

public class A1{
   public int dataA1 {get;set;}
}

public class A2{
   public int dataA2 {get;set;}
}

Type obj= Type.GetType("A2");;

var example = GetData<obj>();

public void GetData<T>(){
   //process T custom (A1 or A2) T = A2
}

2 个答案:

答案 0 :(得分:6)

您应声明一个基类ABase(或使用更好的名称),然后将其用作通用处理的基础:

public class ABase
{
    public int data { get; set; }
}

public class A1 : ABase {
    ... implementation that presumably sets data
}

public class A2 : ABase {
    ... implementation that presumably sets data
}

var example = GetData<ABase>();

public void GetData<T>() where T : ABase {
   // Do something with T which can be A1 or A2 but supports GetData
}

GetData<T>中,您现在可以保证dataA1都可以访问A2属性,因为它是在基类ABase上声明的

或者,您可以实现定义该属性的接口:

public interface IBase
{
    int data { get; set; }
}

public class A1 : IBase {
    // Implement the interface here
    public int data { get; set; }
}

...

在@AnuViswan评论之后编辑

正如任何Viswan所指出的那样,在您的示例(因此也是我的示例)中,GetData<T>不返回任何内容,但将var example设置为方法的结果。

这无疑是您示例中的错字。我猜测GetData<T>应该返回int

答案 1 :(得分:2)

使用接口(或抽象类)。通过这种方式,您只需使用公共父代。


    public interface IA
    {
        public int Data { get; set; }
    } 

    public class A1 : IA
    {
        public int Data { get; set; }
        public A1(int data) => Data = data * 12;
    }

    public class A2 : IA
    {
        public int Data { get; set; }
        public A1(int data) => Data = data / 144;
    }

    public int GetData(IA a) => return a.Data;

    GetData(new A1(1));     // -> 12
    GetData(new A2(144));   // -> 1