연산자 오버로딩(C# 참조)

연산자 오버로드(C# 참조)
사용자 정의 형식은 미리 정의된 C# 연산자를 오버로드할 수 있습니다. 즉, 피연산자 중 하나 또는 두 개가 해당 형식인 경우 형식은 작업의 사용자 정의 구현을 제공할 수 있습니다. 오버로드할 수 있는 연산자 섹션에는 오버로드할 수 있는 C# 연산자가 나와 있습니다.
operator 키워드를 사용하여 연산자를 선언합니다. 연산자 선언은 다음 규칙을 충족해야 합니다.
public 및 static 한정자를 모두 포함합니다.
단항 연산자에는 하나의 입력 매개 변수가 있습니다. 이항 연산자에는 두 개의 입력 매개 변수가 있습니다. 각각의 경우 하나 이상의 매개 변수가 T 또는 T? 유형을 가져야 하며, 여기서 T는 연산자 선언이 포함된 유형입니다.
다음 예제에서는 유리수를 나타내는 간단한 구조를 정의합니다. 구조체가 산술 연산자 중 일부를 오버로드합니다.
C#

using System;

public readonly struct Fraction
{
    private readonly int num;
    private readonly int den;

    public Fraction(int numerator, int denominator)
    {
        if (denominator == 0)
        {
            throw new ArgumentException("Denominator cannot be zero.", nameof(denominator));
        }
        num = numerator;
        den = denominator;
    }

    public static Fraction operator +(Fraction a) => a;
    public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);

    public static Fraction operator +(Fraction a, Fraction b)
        => new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);

    public static Fraction operator -(Fraction a, Fraction b)
        => a + (-b);

    public static Fraction operator *(Fraction a, Fraction b)
        => new Fraction(a.num * b.num, a.den * b.den);

    public static Fraction operator /(Fraction a, Fraction b)
    {
        if (b.num == 0)
        {
            throw new DivideByZeroException();
        }
        return new Fraction(a.num * b.den, a.den * b.num);
    }

    public override string ToString() => $"{num} / {den}";
}

public static class OperatorOverloading
{
    public static void Main()
    {
        var a = new Fraction(5, 4);
        var b = new Fraction(1, 2);
        Console.WriteLine(-a);   // output: -5 / 4
        Console.WriteLine(a + b);  // output: 14 / 8
        Console.WriteLine(a - b);  // output: 6 / 8
        Console.WriteLine(a * b);  // output: 5 / 8
        Console.WriteLine(a / b);  // output: 10 / 4
    }
}

암시적 변환을 int에서 Fraction으로 정의하여 앞의 예제를 확장할 수 있습니다. 그런 다음, 오버로드된 연산자는 해당 두 형식의 인수를 지원합니다. 즉, 분수에 정수를 추가하고 그 결과로 분수를 얻을 수 있습니다.
또한 operator 키워드를 사용하여 사용자 지정 형식 변환을 정의합니다. 자세한 내용은 사용자 정의 변환 연산자를 참조하세요.
오버로드할 수 있는 연산자
다음 표는 C# 연산자의 오버로드 가능성에 대한 정보를 제공합니다.
오버로드할 수 있는 연산자
연산자 오버로드 가능성
+x, -x, !x, ~x, ++, –, true, false 이러한 단항 연산자는 오버로드할 수 있습니다.
x + y, x – y, x * y, x / y, x % y, x & y, x | y, x ^ y, x << y, x >> y, x == y, x != y, x < y, x > y, x <= y, x >= y 이러한 이항 연산자는 오버로드할 수 있습니다. 특정 연산자는 쌍으로 오버로드되어야 합니다. 자세한 내용은 이 표 다음에 나오는 참고 사항을 참조하세요.
x && y, x || y 조건부 논리 연산자는 오버로드할 수 없습니다. 그러나 오버로드된 true 및 false 연산자가 있는 형식도 특정 방식으로 & 또는 | 연산자를 오버로드하는 경우, && 또는 || 연산자는 각각 해당 유형의 피연산자에 대해 평가될 수 있습니다. 자세한 내용은 C# 언어 사양의 사용자 정의 조건부 논리 연산자 섹션을 참조하세요.
a[i], a?[i] 요소 액세스는 오버로드 가능한 연산자로 간주되지 않지만 인덱서를 정의할 수 있습니다.
(T)x 캐스트 연산자는 오버로드될 수 없지만, 캐스트 식에서 수행할 수 있는 사용자 지정 형식 변환을 정의할 수 있습니다. 자세한 내용은 사용자 정의 변환 연산자를 참조하세요.
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= 복합 할당 연산자를 명시적으로 오버로드할 수 없습니다. 그러나 이항 연산자가 오버로드되면 해당 복합 할당 연산자(있는 경우)도 암시적으로 오버로드됩니다. 예를 들어 +=는 오버로드될 수 있는 +를 사용하여 계산됩니다.
^x, x = y, x.y, x?.y, c ? t : f, x ?? y, x ??= y, x..y, x->y, =>, f(x), as, await, checked, unchecked, default, delegate, is, nameof, new, sizeof, stackalloc, switch, typeof, with 이러한 연산자는 오버로드할 수 없습니다.
참고

비교 연산자는 쌍으로 오버로드되어야 합니다. 즉, 쌍 중 하나의 연산자가 오버로드되면 다른 연산자도 오버로드되어야 합니다. 이러한 쌍은 다음과 같습니다.
== 및 != 연산자
< 및 > 연산자
<= 및 >= 연산자
C# 언어 사양

“연산자 오버로딩(C# 참조)”의 85개의 댓글

  1. I know this if off topic but I’m looking into starting my own blog
    and was curious what all is required to get setup?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web smart so I’m not 100% positive. Any recommendations or advice would be greatly appreciated.
    Thank you

    my blog; diets fail part

  2. After looking into a number of the blog articles
    on your web site, I really like your way of writing a
    blog. I saved as a favorite it to my bookmark
    site list and will be checking back soon. Take a look at my
    website as well and let me know what you think.

    Visit my site :: aim simply loss

  3. I would like to express some thanks to this writer for bailing me
    out of this type of problem. Just after browsing throughout the online world and finding
    proposals which were not productive, I assumed my entire
    life was well over. Existing without the presence of answers to the difficulties you have sorted out by means of this short post is a crucial case, and the ones which could have negatively damaged my career if
    I hadn’t encountered your website. Your own personal skills and kindness in handling
    the whole lot was crucial. I don’t know what I would have done if I had not discovered such a thing like this.
    It’s possible to at this point look forward to my future.
    Thanks very much for this impressive and result oriented guide.
    I will not think twice to propose your web blog to any
    person who ought to have tips on this issue.

    My web page; ketosis diet

  4. Good day I am so thrilled I found your web site, I really found
    you by error, while I was searching on Google for something else, Anyways I am here now and would just like to say many
    thanks for a remarkable post and a all round entertaining blog (I also love the theme/design), I don?t have time to look
    over it all at the minute but I have bookmarked it and also
    added in your RSS feeds, so when I have time I will
    be back to read a lot more, Please do keep up the fantastic jo.

    my page – diets bullshit

  5. First off I want to say excellent blog! I had a quick question that I’d like to ask if you do not mind.
    I was curious to find out how you center yourself and clear your thoughts prior
    to writing. I have had a tough time clearing my thoughts in getting my thoughts out there.
    I truly do enjoy writing however it just seems like the first 10 to 15 minutes are generally lost simply just trying to figure out how to begin. Any suggestions or hints?
    Cheers!

    Here is my homepage :: atkins diet weight loss protein based diet revolution diet plan surrounding atkins diet diet book

  6. Does your website have a contact page? I’m having trouble locating it
    but, I’d like to send you an e-mail. I’ve got some recommendations for
    your blog you might be interested in hearing. Either way,
    great website and I look forward to seeing it grow over
    time.

    Here is my web site :: balanced diet

  7. Hi! This is kind of off topic but I need some help from
    an established blog. Is it very difficult to set up your
    own blog? I’m not very techincal but I can figure things
    out pretty fast. I’m thinking about making my own but I’m not sure where to start.

    Do you have any tips or suggestions? Thanks

    Look into my homepage – anti-aging skin care

  8. My partner and I absolutely love your blog and
    find almost all of your post’s to be precisely
    what I’m looking for. Do you offer guest writers to write content in your case?
    I wouldn’t mind writing a post or elaborating on many of
    the subjects you write in relation to here. Again, awesome blog!

    My webpage … fast weight loss

  9. This is the right blog for everyone who wants to find out about this topic.

    You understand a whole lot its almost hard to argue with you
    (not that I personally would want to…HaHa). You definitely put a brand new spin on a topic which has been written about
    for a long time. Great stuff, just excellent!

    My site :: sexual performance

  10. We’re a group of volunteers and opening a new scheme in our community.
    Your web site provided us with valuable information to work on. You’ve done an impressive job and
    our entire community will be grateful to you.

    Feel free to visit my page: good protein

  11. Howdy I am so happy I found your weblog, I
    really found you by error, while I was searching on Digg for something else, Anyways I am here now and would just like to say thanks a lot for
    a incredible post and a all round thrilling blog (I also love the theme/design), I don’t
    have time to go through it all at the minute but I have bookmarked it and also added your
    RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the awesome job.

    Look at my web blog – summer skincare

  12. Thank you for being the tutor on this area. I actually enjoyed your article
    very much and most of all cherished the way you handled the areas I regarded
    as being controversial. You are always extremely
    kind to readers like me and aid me in my everyday living.
    Thank you.

    my blog – gain weight

  13. Wonderful goods from you, man. I’ve understand your stuff previous to
    and you are just extremely excellent. I really like what you have acquired here, certainly like what you are stating and the way in which you say it.

    You make it enjoyable and you still care for to keep it wise.
    I can’t wait to read much more from you. This is
    really a terrific site.

    My blog: concerned hemp

  14. I do not know whether it’s just me or if perhaps everybody else experiencing issues with
    your blog. It looks like some of the text on your content are running off the screen. Can somebody
    else please provide feedback smoking and teens let me
    know if this is happening to them too? This could be a problem with my web browser because I’ve had this happen before.
    Appreciate it

  15. Thank you for your blog post. Johnson and I have already
    been saving to get a new book on this issue and your short
    article has made all of us to save our own money. Your ideas really
    solved all our questions. In fact, in excess of what we had acknowledged before we discovered your wonderful blog.
    My spouse and i no longer nurture doubts including
    a troubled mind because you have attended to our needs above.

    Thanks

    Feel free to surf to my site … fat loss diet

  16. I’m no longer sure the place you’re getting your information, but great topic.
    I needs to spend some time finding out much more or understanding more.
    Thanks for magnificent information I used to be searching for this information for my mission.

    Here is my blog – promote aging

  17. Undeniably believe that which you said. Your favorite reason appeared to be on the web the easiest thing to be aware of.
    I say to you, I certainly get annoyed while people
    consider worries that they plainly do not know about.
    You managed healthy eating to lose weight hit the nail upon the
    top and defined out the whole thing without having side effect , people could take a signal.
    Will probably be back to get more. Thanks

  18. With havin so much content do you ever run into any problems of
    plagorism or copyright violation? My site has a lot of exclusive content I’ve either
    written myself or outsourced but it looks like a lot of it is popping it up all over the web without my agreement.
    Do you know any techniques to help prevent content from being ripped off?
    I’d genuinely appreciate it.

    My blog post – 918kaya agent login

  19. Greate post. Keep posting such kind of information on your page.
    Im really impressed by your site.
    Hey there, You have done a great job. I’ll definitely
    digg it and in my opinion suggest to my friends.
    I am confident they will be benefited from this website.

    Here is my webpage – xe88 game apk

  20. Hey! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for
    some targeted keywords but I’m not seeing very good gains. If you know of any please share.
    Thanks!

    My web page :: http://aldrichdevelopment.com/__media__/js/netsoltrademark.php?d=www.africatopforum.com%2Fclassifiedads%2Fuser%2Fprofile%2F125830

답글 남기기