传递接口时如何访问不同具体类的属性 [英] How to access the property of different concrete classes when interface is passed

查看:51
本文介绍了传递接口时如何访问不同具体类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C#,并试图了解将接口传递给使用者类时如何访问类的不同属性.请引导我.

I am learning C# and trying to understand how to access different property of classes when interface being passed to the consumer class. Please guide me.

public interface ITest
{
    int ID {get; set;}
}

public class TestA: ITest
{
    public int A {get; set;}
}

public class TestB: ITest
{
    public int B {get; set;}
}


public void Test(ITest test)
{
    // how to check/access property of TestA 
    // how to check/access property of TestB
}

尝试:

   public void Test(ITest test)
    {
        if(test.GetType() == typeof(TestA))
        {
             test.A = 45678;
        }
    }

推荐答案

如果您需要对接口的继承者进行特定于实现的操作,请不要嗅探类型...编写特定于实现的方法这个给你.现在,调用者无需进一步了解该接口:

If there's something implementation-specific that you need to do with inheritors of your interface, don't sniff type... write an implementation-specific method to do this for you. Now the caller doesn't need to know anything further about the interface:

void Main()
{
    var tests = new ITest[] { new TestA { A = 1, ID = 0 }, new TestB { B = 10, ID = 1 } };
    foreach (var test in tests)
    {
        test.DoSomeProcessing();
    }
}

public interface ITest
{
    int ID { get; set; }
    void DoSomeProcessing();
}

public class TestA : ITest
{
    public int A { get; set; }
    public int ID { get; set; }
    public void DoSomeProcessing()
    {
        Console.WriteLine("A = " + this.A);
    }
}

public class TestB : ITest
{
    public int B { get; set; }
    public int ID { get; set; }
    public void DoSomeProcessing()
    {
        Console.WriteLine("B = " + this.B);
    }
}

这篇关于传递接口时如何访问不同具体类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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