需要在我的程序中使用C#的特定输出 [英] need a specific output in my programm that in C#

查看:72
本文介绍了需要在我的程序中使用C#的特定输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace ConsoleApplication1
{

   public class A
    {
       public void Methodtoimp()
        {
           // Console.WriteLine("A class call");//what the code
          //  Console.WriteLine("B class call");// have to write here??
        }                                               
    }

  public class B:A
    {
        static void Main(string[] args)
        {

            A obj1=new A();
            obj1.Methodtoimp();
            B obj2=new B ();
            obj2.Methodtoimp();

            Console.Read();
        }
    }
}



上面的代码写的是什么,以便当我调用A对象时,我的输出必须为"A类调用",对于B obj2调用,输出应为"B类调用"

谢谢
Sachin



what the code write above so that when i call the A object the my output must be"A class call" and for B obj2 call output should be "B class call"

Thank you
Sachin

推荐答案

您需要使用this.GetType().Name来获取用于调用的实例的运行时类型并使其简单(不完全合格)名称.因此,它将是:
You need to use this.GetType().Name to obtain the run-time type of the instance used for a call and get its simple (not fully-qualified) name. So, it will be:
Console.WriteLine(string.Format("The run-time type of the calling instance is {0}", this.GetType().Name));
// I don't want to use your incorrect "class call"
// ".this" can be omitted

// or, equivalent simpler form of WriteLine:
Console.WriteLine("The run-time type of the calling instance is {0}", this.GetType().Name);


重要的是要了解您使用实例(非静态)方法.这些方法还有一个附加的(隐藏的,隐式的)参数,称为"this",用于承载变量名称在obj1.Methodtoimp();obj2.Methodtoimp();中的''.''(点)左侧所指定的传递的实例. ,obj1obj2等.

(由于此重载,可能不使用string.Format就能使用System.Console.WriteLine的简化形式: http://msdn .microsoft.com/en-us/library/828t9b9h.aspx [ ^ ].)

我还想警告您,使用类型对象,类型名称或类似的东西来定义您的代码逻辑将是违反OOP目的的大滥用.使用OOP时,应基于虚拟方法和覆盖方法和/或接口使用 late绑定.好吧,到目前为止,您还没有做任何坏事...

—SA


It''s important to understand that you use instance (non-static) methods. These method has additional (hidden, implicit) parameter called "this", used to carry the instance passed as specified by your variable name on the left part of ''.'' (dot) in obj1.Methodtoimp(); or obj2.Methodtoimp(); that is, obj1, obj2 or the like.

(Simplified form of System.Console.WriteLine without using string.Format is possible because of this overload: http://msdn.microsoft.com/en-us/library/828t9b9h.aspx[^].)

I would also want to warn you that using the type object, type name or something like this to define logic of your code would be the big abuse defeating the purpose of OOP. With OOP, you should use late binding based on virtual and overridden methods and/or interfaces. Well, so far, you are not doing anything bad…

—SA


您需要在类B和类A中定义Methodtoimp,然后在其中包含适当的WriteLine语句每个类的实现.
You need to define Methodtoimp in class B as well as class A, then just include the appropriate WriteLine statement in each class''s implementation.


这篇关于需要在我的程序中使用C#的特定输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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