方法调用C# [英] Method Invocation C#

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

问题描述

如何在不使用点运算符,此关键字和C#.net中的反射的情况下从另一个类调用类方法?

How to call a class method from another class without using a dot operator,this keyword and Reflection in C#.net ?

推荐答案

只需在内部调用您的方法您将在课堂内使用的方法.或者,您可以使用this关键字,它将显示所有类成员.
http://msdn.microsoft.com/en-us/library/dk1507sz%28v = vs.100%29.aspx [ ^ ]
Just call your method inside the method you going to use inside of your class. Or you can use the this keyword and it will show all the classes members.
http://msdn.microsoft.com/en-us/library/dk1507sz%28v=vs.100%29.aspx[^]


点不是运算符.

好吧,点是一个词法元素,除其他外,它用于使实例的引用限定类型的成员,该实例的引用用作实例(非静态)方法或属性的"this"参数或用作类名如果是静态成员.就像在实例(非静态)方法的主体中一样,假定"this"为"this".可以省略,这使您可以呼叫或访问不带点的成员.对于静态成员,假定使用一个声明的类,因此可以使用带点的类名称.

即:
Dot is not an operator.

Well, dot is a lexical element used, among other things, to qualify a member of a type with a reference of an instance which is used as a "this" parameter for instance (non-static) methods or properties or as a class name in case of static members. As in a body of an instance (non-static) method "this" is assumed, "this." can be omitted, which gives you a call or an access to a member without dot. For static members, a declaring class is assumed, so class name with a dot could be used.

That is:
class MyClass {

    void InstanceMethod(/* "this" is passed implicitly */) {
        //working with instance members:
        a = 1; // this.a assumed
        this.b = 2;
        MethodA(/*"this" passed */); //this.Method A assumed
        this.MethodB();
        //
        //working with static members:
        c = 3; //MyClass.c assumed
        MyClass.d = 4;
        MethodC(); //MyClass.MethodC assumed
        MyClass.MethodD();
    } //InstanceMethod

    static void StaticMethod() {
        //working with instance members would not compile;
        //instance is not known (no "this"):
        /*
        a = 1; // this.a assumed
        this.b = 2;
        MethodA(/*"this" passed */); //this.Method A assumed
        this.MethodB();
        */
        //
        //working with static members is only allowed:
        c = 3; //MyClass.c assumed
        MyClass.d = 4;
        MethodC(); //MyClass.MethodC assumed
        MyClass.MethodD();
    } //InstanceMethod

    //instance members:
    int a, b;
    void MethodA() {/*...*/}
    void MethodB() {/*...*/}

    //static members:
    static int c, d;
    static void MethodC() {/*...*/}
    static void MethodD() {/*...*/}

    //...

} //class MyClass



另请参阅我过去的答案:
什么使静态方法可访问? [



See also my past answer:
What makes static methods accessible?[^].

—SA


var type = typeof(TestClass);
var method = type.GetMethod("Print");
method.Invoke(null,null);





public class TestClass
{
    public static void Print()
    {
        Debug.Write("### Print Method Invoked");
    }
}


这篇关于方法调用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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