简体   繁体   English

C#类类型作为方法参数

[英]C# class type as method parameter

public class SampleCass{
  public void DoSomething(SampleCass sample){

       //Do method implementation
 }
}

In the above code sample, the method parameter type passed is same as the class to which the method belongs to. 在上面的代码示例中,传递的方法参数类型与该方法所属的类相同。 I wanted to know why it is done this way and also some details on it 我想知道为什么这样做,还有一些细节

Thanks in advance 提前致谢

This can have may uses. 这可以有可能的用途。 Consider for instance a Number class (dumb): 例如考虑一个数字类(哑):

public class Number {
    private readonly int _n = 0;

    public Number(int n) { _n = n; }

    public Number Add(Number other) {
         return new Number(this._n + other._n);
    }
}

That's because that method uses an instance of that class other than its own to do something. 这是因为该方法使用该类的实例而不是其自己的实例来做某事。 Imagine you have a Contact type and a method that compares it to another contact. 假设您有一个“联系人”类型和一种将其与另一个联系人进行比较的方法。 You can make this: 您可以这样做:

public class Contact
{        
   public string name;

    public bool Compare(Contact c)
    {
       return this.name.Equals(c.name);
    }
}

If I had to guess, I would say it is done this way, because logic inside method uses two instances of the object - one upon which method is called ( this ), and one passed trough the parameter ( sample ). 如果我不得不猜测,我会说是这样做的,因为方法内部的逻辑使用该对象的两个实例 -一个在其上调用方法( this ),另一个通过参数( sample )传递。 If logic inside method does not use both instances of the object, something might be done wrong. 如果方法内部的逻辑未同时使用对象的两个实例,则可能做错了什么。

Hope this helps, for more details we need to see more code. 希望这会有所帮助,有关更多详细信息,我们需要查看更多代码。

Well, there can be many uses depending upon your problem domain. 好吧,根据您的问题领域,可以有很多用途。 I can give you another example where you can write fields of same type as of the class. 我可以举另一个例子,您可以在其中编写与该类相同类型的字段。

eg: 例如:

public class Node
{
  public Node _next;
}

I know your question is very particular but I thought this example can add value to the current question. 我知道您的问题非常特殊,但是我认为这个示例可以为当前问题增加价值。

(I am giving a constructor example, which will help you in understanding non-constructor methods.) (我提供了一个构造函数示例,它将帮助您理解非构造方法。)

This can be used to create copy constructor like 这可以用来创建复制构造函数,例如

public class SampleCass
{
    public int MyInteger { get; set;}

    //Similarly other properties

    public SampleClass(SampleClass tocopyfrom)
    {
            MyInteger = tocopyfropm.MyInteger;
           //Similarly populate other properties
    }
}

can can be called like this 可以这样称呼

SampleClass copyofsc = new SampleClass(originalsc);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM