传递接口时如何访问不同具体类的属性

编程入门 行业动态 更新时间:2024-10-26 14:37:27
本文介绍了传递接口时如何访问不同具体类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习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); } }

更多推荐

传递接口时如何访问不同具体类的属性

本文发布于:2023-11-12 09:44:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581152.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   接口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!