연산자 오버로딩(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# 참조)”의 305개의 댓글

  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. Hiya very nice site!! Man .. Excellent .. Wonderful ..
    I’ll bookmark your blog and take the feeds additionally?I’m happy to search
    out so many useful information here in the post, we want develop extra techniques on this regard, thanks for sharing.

    my web page :: vaginal orgasms

  13. 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

  14. I haven’t checked in here for some time because I thought it was getting boring, but the last few posts are great
    quality so I guess I’ll add you back to my everyday bloglist.
    You deserve it friend 🙂

    Here is my web-site – boost libido

  15. 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

  16. 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

  17. Great work! That is the type of information that are meant to be shared
    across the web. Disgrace on Google for not positioning this publish higher!

    Come on over and talk over with my site . Thank you =)

    my web page :: care tips

  18. 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

  19. 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

  20. 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

  21. Great article and straight to the point. I am not sure if this is truly the best place to ask but do you folks have any ideea where to employ some professional writers? Thanks in advance 🙂

  22. Hi, I do think this is a great site. I stumbledupon it
    😉 I am going to return yet again since I book marked it.
    Money and freedom is the greatest way to change, may you be rich
    and continue to guide others.

    Also visit my website :: download pussy888 (rockfishlax.com)

  23. 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

  24. 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

  25. 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

  26. After I initially commented I appear to have clicked the -Notify me
    when new comments are added- checkbox and from now on each time a comment is added I recieve four emails with the same comment.
    There has to be an easy method you can remove me from that service?
    Cheers!

    Look at my blog post smfpt2.smfpt.net

  27. Sedentary lifestyle claims more than 4 million direct victims each year
    cialis 5mg price comparison cialis free trial coupon viagra cialis levitra

    According to a recent study, lack of physical activity is the main risk factor for premature mortality for the entire world population.
    This paper highlights the percentage of deaths that can be attributed to sedentary lifestyles worldwide. An alarming conclusion is that a sedentary lifestyle is the main risk factor for many non-communicable diseases. These include cardiovascular disease, coronary artery disease, stroke, hypertension, and type 2 diabetes. There are also cancers (bladder, stomach, kidney, breast, colon, and esophagus), depression, and dementia.
    brand cialis when does cialis patent expire what is cialis for
    A study published in the British Medical Journal of Sports Medicine on March 29, 2021, estimates that physical inactivity is responsible for 7.2% of all-cause deaths each year. This represents about 4 million deaths out of an average of 56.9 million per year. The American and Canadian researchers behind this work obtained information from several databases in different states. In addition, they tried to get the results closest to reality by considering pathologies whose causal relationship with a sedentary lifestyle is well known. In other words, we are talking about a serious level of evidence. According to the results, in developing countries, most deaths (in absolute numbers) occur due to the lack of physical activity of a part of their population. On the other hand, developed countries are more likely to suffer from the effects of a sedentary lifestyle, as they are subject to a much higher percentage of deaths. The study’s authors strongly believe that ” the public health burden associated with physical inactivity is a global problem that will require international cooperation to mobilize change and achieve these public health goals.” For researchers, change should be focused on achieving public health goals. This means increased investment in the re-opening of sports facilities during the pandemic. It also means making them available to as many people as possible in the long run.
    viagra and cialis together how many years can you take cialis? brand cialis

  28. Sedentary lifestyle claims more than 4 million direct victims each year
    is 20mg cialis equal to 100mg viagra cialis generic canada cialis

    According to a recent study, lack of physical activity is the main risk factor for premature mortality for the entire world population.
    This paper highlights the percentage of deaths that can be attributed to sedentary lifestyles worldwide. An alarming conclusion is that a sedentary lifestyle is the main risk factor for many non-communicable diseases. These include cardiovascular disease, coronary artery disease, stroke, hypertension, and type 2 diabetes. There are also cancers (bladder, stomach, kidney, breast, colon, and esophagus), depression, and dementia.
    canadian pharmacy cialis ed cialis cialis 5mg daily how long before it works
    A study published in the British Medical Journal of Sports Medicine on March 29, 2021, estimates that physical inactivity is responsible for 7.2% of all-cause deaths each year. This represents about 4 million deaths out of an average of 56.9 million per year. The American and Canadian researchers behind this work obtained information from several databases in different states. In addition, they tried to get the results closest to reality by considering pathologies whose causal relationship with a sedentary lifestyle is well known. In other words, we are talking about a serious level of evidence. According to the results, in developing countries, most deaths (in absolute numbers) occur due to the lack of physical activity of a part of their population. On the other hand, developed countries are more likely to suffer from the effects of a sedentary lifestyle, as they are subject to a much higher percentage of deaths. The study’s authors strongly believe that ” the public health burden associated with physical inactivity is a global problem that will require international cooperation to mobilize change and achieve these public health goals.” For researchers, change should be focused on achieving public health goals. This means increased investment in the re-opening of sports facilities during the pandemic. It also means making them available to as many people as possible in the long run.
    otc cialis cialis and bph cialis india

  29. I have not checked in here for a while as I thought it was getting boring, but the last several posts are
    great quality so I guess I will add you back to my daily bloglist.

    You deserve it friend 🙂

    my website … e-hp.info

  30. Have you ever considered writing an e-book or
    guest authoring on other websites? I have a blog centered on the same information you discuss and would really like to have you share some stories/information. I know my subscribers would enjoy your work.
    If you’re even remotely interested, feel free to send me an e-mail.

    Feel free to visit my blog … http://www.ankarac.com/index.php?action=profile;u=5920

  31. Wonderful goods from you, man. I have understand your stuff prior to
    and you are just extremely wonderful. I actually like what you
    have acquired right here, really like what you’re saying
    and the way in which by which you are saying it.
    You make it entertaining and you still care for to keep it wise.
    I can’t wait to read far more from you. That is actually a terrific web site.

    Also visit my web-site :: http://www.consulenzaleonardo.com

  32. It’s a shame you don’t have a donate button! I’d definitely
    donate to this excellent blog! I suppose for now i’ll settle for bookmarking and adding your
    RSS feed to my Google account. I look forward to fresh updates and will share this
    website with my Facebook group. Talk soon!

    My blog post – kanin.ca

  33. I just couldn’t depart your site before suggesting that I really enjoyed the standard information a person provide for your visitors? Is going to be back often to check up on new posts

  34. Great post. I used to be checking continuously this weblog and I am impressed!
    Very helpful info specifically the remaining part 🙂 I maintain such information much.
    I used to be seeking this particular info for a very long time.
    Thanks and best of luck.

    Here is my site … freeholmes.com

  35. I’m not sure exactly why but this web site is loading incredibly slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later on and see if the problem still exists.

  36. Hi! I understand this is sort of off-topic but I had to ask.
    Does managing a well-established website such as yours
    require a massive amount work? I am brand new to blogging however I do write in my journal daily.
    I’d like to start a blog so I can share my experience
    and thoughts online. Please let me know if you have any kind of suggestions or tips for new aspiring
    bloggers. Thankyou!

    Have a look at my web-site – https://kebe.top/

  37. Hey just wanted to give you a quick heads up. The words in your post seem to be running
    off the screen in Ie. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I
    thought I’d post to let you know. The layout look great though!
    Hope you get the issue resolved soon. Thanks

    Feel free to surf to my web blog – cs.yyqyt.com

  38. I comment when I especially enjoy a article on a
    website or I have something to valuable to contribute to the conversation. It is triggered by the sincerness displayed in the post I looked at.

    And on this article 연산자 오버로딩(C# 참조) | 기록은
    자산. I was moved enough to post a thought 😉 I do have some questions for you if it’s
    allright. Is it just me or do a few of the comments appear
    like written by brain dead individuals? 😛 And,
    if you are writing at other social sites, I’d like to keep up with
    you. Could you make a list the complete urls of all your public pages like your Facebook page, twitter feed, or linkedin profile?

    Review my web site … http://www.craksracing.com

  39. You can play select versions of mobile games for free online right at Miniclip.com without the need to own a mobile phone. If you have a mobile phone you can try the games for free on Miniclip and then download them to your iPhone, Android or Windows Phone to play on the go. Flash, the beloved platform we all know and love for its classic games, and animation, will cease to exist as of January 2021. Always controversial, sometimes ground-breaking, but never boring, Flash will be gone, baleeted forever, marched away with the black parade as early as New Years Day. http://86x.org/home.php?mod=space&uid=248532 To conclude, we approximated the landing probability using Monte Carlo simulation, so as to compute the break-even point and the expected profit of each colour set with a certain number of houses in an N-player game. Based on the above-mentioned observations and strategies, we summarize the following 7 strategies that you should follow. While Xbox Monopoly is great for multiplayer games online, each player must have their own Xbox. You can’t for example, play the game with four players on two Xboxes, there’s sadly no option for that. You also can’t play together if one person has an Xbox One and one has an Xbox 360.

답글 남기기