简体   繁体   English

如何对具有相同成员的不同类型参数使用相同的函数?

[英]How can I use the same function for different type parameters which have the same member?

BHere is the sample code, I've defined two classes. BHere是示例代码,我已经定义了两个类。 How can I use the Output function to output the member which has the same name in two different classes? 如何使用Output函数输出两个不同类中具有相同名称的成员?

class A
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }

    public A(string name, int age, string email)
    {
        Name = name;
        Age = age;
        Email = email;
    }
}

class B
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Location { get; set; }

    public B(string name, int age, string location)
    {
        Name = name;
        Age = age;
        Location = location;
    }
}

void Output(object obj)
{
    // How can I convert the object 'obj' to class A or class B
    // in order to output its 'Name' and 'Age'
    Console.WriteLine((A)obj.Name); // If I pass a class B in pararmeter, output error.
}

You'd have to either: 你必须要么:

  1. Use Reflection to get the property (and throw if it isn't there) 使用Reflection获取属性(如果不存在则抛出)
  2. Have a common interface, such as INamed that has a string Name property, that each of the two classes implement 有一个通用接口,例如INamed ,它具有一个字符串Name属性,即两个类中的每一个都实现
  3. Declare a local variable as dynamic and use it to access the Name property (but in effect this is the same as #1, because the dynamic dispatch will merely use Reflection to get the Name property). 将局部变量声明为dynamic并使用它来访问Name属性(但实际上这与#1相同,因为动态分派仅使用Reflection来获取Name属性)。

You can take advantage of dynamic to bypass the compiler, it checks the type at runtime so you don't need to cast: 您可以利用dynamic来绕过编译器,它会在运行时检查类型,因此您不需要强制转换:

void Output(dynamic obj)
{
    Console.WriteLine(obj.Name); 
}

You should declare an interface which will describe the common part of both classes: 您应该声明一个接口,它将描述两个类的公共部分:

interface I
{
    string Name { get; set; }
    int Age { get; set; }
}

Then implement it in both A and B : 然后在AB实现它:

class A : I
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }

    public A(string name, int age, string email)
    {
        Name = name;
        Age = age;
        Email = email;
    }
}

class B : I
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Location { get; set; }

    public B(string name, int age, string location)
    {
        Name = name;
        Age = age;
        Location = location;
    }
}

And change your method to get I as parameter: 并改变你的方法让I作为参数:

void Output(I obj)
{
    Console.WriteLine(obj.Name); 
}

You could use dynamic , reflection, or inheritance. 您可以使用dynamic ,反射或继承。 Or you could just duplicate the method and take advantage of method overloading 或者你可以复制方法并利用方法重载

void Output(A obj)
{
 // in order to output its 'Name' and 'Age'
 Console.WriteLine(obj.Age);
 Console.WriteLine(obj.Name);
}

void Output(B obj)
{
 // in order to output its 'Name' and 'Age'
 Console.WriteLine(obj.Age);
 Console.WriteLine(obj.Name);
}

You need to create a common interface for both classes, so the compiler knows that both classes can dliver certain features (Name and age in your case): 您需要为这两个类创建一个公共接口,因此编译器知道这两个类都可以提供某些功能(在您的情况下为Name和age):

    interface IHasNameAndAge
    {
        string Name { get; }
        int Age { get; }
    }

    class A : IHasNameAndAge
    {
        public string Name { get; set; }
        public int Age { get; set; }
        string Email { get; set; }

        public A(string name, int age, string email)
        {
            Name = name;
            Age = age;
            Email = email;
        }
    }

    class B : IHasNameAndAge
    {
        public string Name { get; set; }
        public int Age { get; set; }
        string Location { get; set; }

        public A(string name, int age, string location)
        {
            Name = name;
            Age = age;
            Location = location;
        }
    }

    void Output(IHasNameAndAge obj)
    {
        Console.WriteLine(obj.Name + " is " + obj.Age);
    }

In your case - B does not inheret from A, so you cannot cast B to A. 在你的情况下 - B不存在于A中,所以你不能将B投射到A.

Change B to inherit from A, like 改变B继承自A,就像

class B : A
{
...
}

Also - consider what are you trying to accomplish in your A() method of B class. 另外 - 考虑一下你在B类的A()方法中想要完成什么。 And - if you inherited, you probably need not same members to be declared twice. 而且 - 如果你继承了,你可能不需要声明两次相同的成员。

You could do: 你可以这样做:

if ( obj.GetType() == typeof( A ) )
{
    Console.WriteLine(((A)obj).Name);
}
else if ( obj.GetType() == typeof( B ) )
{
    Console.WriteLine(((B)obj).Name);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何对具有相同类型和名称的变量的不同结构使用通用类型参数? - How can I use a generic type parameter for different structs that have a variable with the same type and name? 如何使用Reflection Emit定义具有相同名称和不同类型参数的多个类型? - How can I define multiple types with the same name and different type parameters using Reflection Emit? 如何辨别列表中的哪些对象与相同类型的另一个对象最相似? - How can I tell which objects in a list have the most in common with another object of the same type? 对于具有相同扩展名(在同一文件夹中)的不同文件,我可以有不同的 MIME 类型映射吗? - Can I have different MIME type mappings for different files with the same extension (in the same folder)? 使用具有两种相同但名称不同的两种类型的API。 如何重用我的代码? - Consuming an API which has a two types which are the same but have different names. How can I reuse my code? 如何在同一函数中传递不同数量的参数? - How to pass different numbers of parameters in a same function? 是否可以将具有相同返回类型但参数不同的函数发送给另一个函数? - Is it possible to send a function to another function with the same return type but different parameters? 我可以在不同的 ASP.NET 页面中使用相同的 function 吗? - Can I use the same function in different ASP.NET pages? 如何引用具有相同名称的2个不同的DLL? - How can I reference 2 different DLLs that have the same name? 如何加载相同的 Blazor 页面并使用不同的参数访问相同的 url 并将参数显示到 Blazor 中的 UI? - How can I load the same Blazor page hitting same url with different parameters and show the parameter to UI in Blazor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM