블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2737)
Unity3D (817)
Programming (474)
Python (8)
TinyXML (5)
STL (13)
D3D (3)
MFC (1)
C/C++ (54)
C++/CLI (45)
C# (250)
WinForm (6)
WPF (5)
Math (10)
A.I. (1)
Win32API (11)
Algorithm (3)
Design Pattern (7)
UML (1)
MaxScript (1)
FMOD (4)
FX Studio (1)
Lua (2)
Terrain (1)
Shader (3)
boost (2)
Xml (2)
JSON (4)
Etc (11)
Monad (1)
Html5 (4)
Qt (1)
Houdini (0)
Regex (10)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-19 00:04


Google Protocol Buffer 사용해보기 with C# - 첫번째




Google Protocol Buffer 사용해보기 with C# - 세번째


반응형

'Programming > C#' 카테고리의 다른 글

Sort a Custom Class List<T>  (0) 2014.09.29
Sheet Name에 만들지도 않은 '_xlnm#_FilterDatabase'이 포함된 Sheet가 보일 때..  (0) 2014.09.17
Calendar Class[MSDN]  (0) 2014.09.01
C# 강의  (0) 2014.08.29
람다 식  (0) 2014.08.29
Posted by blueasa
, |

Calendar Class[MSDN]

Programming/C# / 2014. 9. 1. 11:45

Link : http://msdn.microsoft.com/en-us/library/system.globalization.calendar(v=vs.110).aspx


Calendar Class

.NET Framework 4.5
1 out of 5 rated this helpful Rate this topic

Represents time in divisions, such as weeks, months, and years.

Inheritance Hierarchy

System.Object 
  System.Globalization.Calendar
    More...

Namespace:  System.Globalization
Assembly:  mscorlib (in mscorlib.dll)

Syntax

[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Calendar : ICloneable

The Calendar type exposes the following members.

Constructors

Show: 
 NameDescription
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsCalendarInitializes a new instance of the Calendar class.
Top

Properties

Show: 
 NameDescription
Public propertyAlgorithmTypeGets a value indicating whether the current calendar is solar-based, lunar-based, or a combination of both.
Protected propertyDaysInYearBeforeMinSupportedYearGets the number of days in the year that precedes the year that is specified by theMinSupportedDateTime property.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsErasWhen overridden in a derived class, gets the list of eras in the current calendar.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsReadOnlyGets a value indicating whether this Calendar object is read-only.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMaxSupportedDateTimeGets the latest date and time supported by thisCalendar object.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMinSupportedDateTimeGets the earliest date and time supported by thisCalendar object.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsTwoDigitYearMaxGets or sets the last year of a 100-year range that can be represented by a 2-digit year.
Top

Methods

Show: 
 NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddDaysReturns a DateTime that is the specified number of days away from the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddHoursReturns a DateTime that is the specified number of hours away from the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddMillisecondsReturns a DateTime that is the specified number of milliseconds away from the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddMinutesReturns a DateTime that is the specified number of minutes away from the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddMonthsWhen overridden in a derived class, returns a DateTime that is the specified number of months away from the specifiedDateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddSecondsReturns a DateTime that is the specified number of seconds away from the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddWeeksReturns a DateTime that is the specified number of weeks away from the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddYearsWhen overridden in a derived class, returns a DateTime that is the specified number of years away from the specifiedDateTime.
Public methodCloneCreates a new object that is a copy of the current Calendarobject.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDayOfMonthWhen overridden in a derived class, returns the day of the month in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDayOfWeekWhen overridden in a derived class, returns the day of the week in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDayOfYearWhen overridden in a derived class, returns the day of the year in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDaysInMonth(Int32, Int32)Returns the number of days in the specified month and year of the current era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDaysInMonth(Int32, Int32, Int32)When overridden in a derived class, returns the number of days in the specified month, year, and era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDaysInYear(Int32)Returns the number of days in the specified year of the current era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDaysInYear(Int32, Int32)When overridden in a derived class, returns the number of days in the specified year and era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetEraWhen overridden in a derived class, returns the era in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHourReturns the hours value in the specified DateTime.
Public methodGetLeapMonth(Int32)Calculates the leap month for a specified year.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetLeapMonth(Int32, Int32)Calculates the leap month for a specified year and era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetMillisecondsReturns the milliseconds value in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetMinuteReturns the minutes value in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetMonthWhen overridden in a derived class, returns the month in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetMonthsInYear(Int32)Returns the number of months in the specified year in the current era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetMonthsInYear(Int32, Int32)When overridden in a derived class, returns the number of months in the specified year in the specified era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetSecondReturns the seconds value in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetWeekOfYearReturns the week of the year that includes the date in the specified DateTime value.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetYearWhen overridden in a derived class, returns the year in the specified DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsLeapDay(Int32, Int32, Int32)Determines whether the specified date in the current era is a leap day.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsLeapDay(Int32, Int32, Int32, Int32)When overridden in a derived class, determines whether the specified date in the specified era is a leap day.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsLeapMonth(Int32, Int32)Determines whether the specified month in the specified year in the current era is a leap month.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsLeapMonth(Int32, Int32, Int32)When overridden in a derived class, determines whether the specified month in the specified year in the specified era is a leap month.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsLeapYear(Int32)Determines whether the specified year in the current era is a leap year.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsLeapYear(Int32, Int32)When overridden in a derived class, determines whether the specified year in the specified era is a leap year.
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited fromObject.)
Public methodStatic memberReadOnlyReturns a read-only version of the specified Calendar object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32)Returns a DateTime that is set to the specified date and time in the current era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32)When overridden in a derived class, returns a DateTime that is set to the specified date and time in the specified era.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToFourDigitYearConverts the specified year to a four-digit year by using theTwoDigitYearMax property to determine the appropriate century.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Top

Fields

Show: 
 NameDescription
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsCurrentEraRepresents the current era of the current calendar.
Top

Remarks

A calendar divides time into units, such as weeks, months, and years. The number, length, and start of the divisions vary in each calendar.

NoteNote

For information about using the calendar classes in the .NET Framework, see Working with Calendars.

Any moment in time can be represented as a set of numeric values using a particular calendar. For example, a vernal equinox occurred at (1999, 3, 20, 8, 46, 0, 0.0) in the Gregorian calendar, that is, March 20, 1999 C.E. at 8:46:00:0.0. An implementation of Calendar can map any date in the range of a specific calendar to a similar set of numeric values, and DateTime can map such sets of numeric values to a textual representation using information from Calendar and DateTimeFormatInfo. The textual representation can be culture-sensitive, for example, "8:46 AM March 20th 1999 AD" for the en-US culture, or culture-insensitive, for example, "1999-03-20T08:46:00" in ISO 8601 format.

Calendar implementation can define one or more eras. The Calendar class identifies the eras as enumerated integers, where the current era (CurrentEra) has the value 0.

To make up for the difference between the calendar year and the actual time that the earth rotates around the sun or the actual time that the moon rotates around the earth, a leap year has a different number of days from a standard calendar year. Each Calendar implementation defines leap years differently.

For consistency, the first unit in each interval (the first month, for example) is assigned the value 1.

The System.Globalization namespace includes the following Calendar implementations:

Examples

The following code example demonstrates the members of the Calendar class.

using System;
using System.Globalization;


public class SamplesCalendar  {

   public static void Main()  {

      // Sets a DateTime to April 3, 2002 of the Gregorian calendar.
      DateTime myDT = new DateTime( 2002, 4, 3, new GregorianCalendar() );

      // Uses the default calendar of the InvariantCulture.
      Calendar myCal = CultureInfo.InvariantCulture.Calendar;

      // Displays the values of the DateTime.
      Console.WriteLine( "April 3, 2002 of the Gregorian calendar:" );
      DisplayValues( myCal, myDT );

      // Adds 5 to every component of the DateTime.
      myDT = myCal.AddYears( myDT, 5 );
      myDT = myCal.AddMonths( myDT, 5 );
      myDT = myCal.AddWeeks( myDT, 5 );
      myDT = myCal.AddDays( myDT, 5 );
      myDT = myCal.AddHours( myDT, 5 );
      myDT = myCal.AddMinutes( myDT, 5 );
      myDT = myCal.AddSeconds( myDT, 5 );
      myDT = myCal.AddMilliseconds( myDT, 5 );

      // Displays the values of the DateTime.
      Console.WriteLine( "After adding 5 to each component of the DateTime:" );
      DisplayValues( myCal, myDT );

   }

   public static void DisplayValues( Calendar myCal, DateTime myDT )  {
      Console.WriteLine( "   Era:          {0}", myCal.GetEra( myDT ) );
      Console.WriteLine( "   Year:         {0}", myCal.GetYear( myDT ) );
      Console.WriteLine( "   Month:        {0}", myCal.GetMonth( myDT ) );
      Console.WriteLine( "   DayOfYear:    {0}", myCal.GetDayOfYear( myDT ) );
      Console.WriteLine( "   DayOfMonth:   {0}", myCal.GetDayOfMonth( myDT ) );
      Console.WriteLine( "   DayOfWeek:    {0}", myCal.GetDayOfWeek( myDT ) );
      Console.WriteLine( "   Hour:         {0}", myCal.GetHour( myDT ) );
      Console.WriteLine( "   Minute:       {0}", myCal.GetMinute( myDT ) );
      Console.WriteLine( "   Second:       {0}", myCal.GetSecond( myDT ) );
      Console.WriteLine( "   Milliseconds: {0}", myCal.GetMilliseconds( myDT ) );
      Console.WriteLine();
   }

}


/*
This code produces the following output.

April 3, 2002 of the Gregorian calendar:
   Era:          1
   Year:         2002
   Month:        4
   DayOfYear:    93
   DayOfMonth:   3
   DayOfWeek:    Wednesday
   Hour:         0
   Minute:       0
   Second:       0
   Milliseconds: 0

After adding 5 to each component of the DateTime:
   Era:          1
   Year:         2007
   Month:        10
   DayOfYear:    286
   DayOfMonth:   13
   DayOfWeek:    Saturday
   Hour:         5
   Minute:       5
   Second:       5
   Milliseconds: 5

*/

Version Information

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Platforms

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.



반응형
Posted by blueasa
, |

C# 강의

Programming/C# / 2014. 8. 29. 14:35


Link : http://mrw0119.tistory.com/category/C%23

반응형

'Programming > C#' 카테고리의 다른 글

Google Protocol Buffer 사용해보기 with C#  (0) 2014.09.16
Calendar Class[MSDN]  (0) 2014.09.01
람다 식  (0) 2014.08.29
Get Dictionary key by using the dictionary value  (0) 2014.08.12
[C#] How to get/set using index for a Dictionary?  (0) 2014.08.06
Posted by blueasa
, |

람다 식

Programming/C# / 2014. 8. 29. 14:16

출처 : http://msdn.microsoft.com/ko-kr/library/bb397687.aspx



람다 식(C# 프로그래밍 가이드)

Visual Studio 2013
3명 중 3명이 도움이 되는 것으로 평가 이 항목 평가

람다 식은 대리자 또는 식 트리 형식을 만드는 데 사용할 수 있는 익명 함수입니다. 람다 식을 사용하여 인수로 전달되거나 함수 호출 값으로 반환되는 로컬 함수를 쓸 수 있습니다. 람다 식은 LINQ 쿼리 식을 작성하는 데 특히 유용합니다.

람다 식을 만들려면 람다 연산자 => 왼쪽에 입력 매개 변수를 지정하고(있는 경우) 다른 쪽에 식이나 문 블록을 삽입합니다. 예를 들어 람다 식 x => x * x는 이름이 x인 매개 변수를 지정하고 x 제곱 값을 반환합니다. 다음 예제와 같이 대리자 형식에 이 식을 할당할 수도 있습니다.

delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}

식 트리 형식을 만들려면

using System.Linq.Expressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<del> myET = x => x * x;
        }
    }
}

=> 연산자는 할당(=)과 우선 순위가 같고 오른쪽 결합성이 있습니다(연산자 문서의 "결합성" 단원 참조).

람다 식은 메서드 기반 LINQ 쿼리에서 Where 같은 표준 쿼리 연산자 메서드의 인수로 사용됩니다.

LINQ to Objects 및 LINQ to XML에서처럼 메서드 기반의 구문을 사용하여 Enumerable 클래스에서 Where 메서드를 호출하는 경우 매개 변수는System.Func<T, TResult> 대리자 형식입니다. 람다 식은 이러한 대리자를 만드는 가장 간단한 방법입니다. 예를 들어 LINQ to SQL에서처럼 이 메서드를System.Linq.Queryable 클래스에서 호출하는 경우 매개 변수 형식은 System.Linq.Expressions.Expression<Func>이고, 여기서 Func는 입력 매개 변수를 16개까지 가질 수 있는 임의의 Func 대리자입니다. 이 경우에도 람다 식을 사용하면 식 트리를 간단하게 만들 수 있습니다. 람다 식은 Where 호출과 비슷하게 보일 수 있지만 실제로 람다 식을 통해 생성되는 개체 형식은 다릅니다.

위의 예제에서 대리자 시그니처는 형식이 암시적으로 지정된 int 형식의 입력 매개 변수 하나를 포함하고 int를 반환합니다. 람다 식에도 입력 매개 변수 하나(x)와 컴파일러에서 int 형식으로 암시적으로 변환할 수 있는 반환 값이 있기 때문에 람다 식을 이 형식의 대리자로 변환할 수 있습니다. 형식 유추는 다음 단원에서 자세하게 설명합니다. 입력 매개 변수를 5로 사용하여 대리자를 호출하면 25라는 결과가 반환됩니다.

is 또는 as 연산자의 왼쪽에는 람다 식을 사용할 수 없습니다.

무명 메서드에 적용되는 모든 제한은 람다 식에도 적용됩니다. 자세한 내용은 무명 메서드(C# 프로그래밍 가이드)을 참조하십시오.

=> 연산자의 오른쪽에 식이 있는 람다 식을 식 람다라고 합니다. 식 람다는 식 트리(C# 및 Visual Basic)를 만드는 데 광범위하게 사용됩니다. 식 람다는 식의 결과를 반환하며 기본 형식은 다음과 같습니다.

(input parameters) => expression

괄호는 람다 식에 입력 매개 변수가 하나뿐인 경우에만 생략할 수 있고 그렇지 않으면 생략할 수 없습니다. 둘 이상의 입력 매개 변수는 다음과 같이 괄호로 묶고 쉼표로 구분해야 합니다.

(x, y) => x == y

컴파일러에서 입력 형식을 유추할 수 없는 경우도 있습니다. 이와 같은 경우에는 다음 예제와 같이 형식을 명시적으로 지정할 수 있습니다.

(int x, string s) => s.Length > x

입력 매개 변수가 0개이면 다음과 같이 빈 괄호를 지정합니다.

() => SomeMethod()

위의 예제에서 식 람다의 본문은 메서드 호출로 구성될 수 있습니다. 하지만 SQL Server와 같은 .NET Framework 외부에서 평가되는 식 트리를 만드는 경우에는 람다 식에 메서드 호출을 사용하지 않아야 합니다. 이러한 메서드는 .NET 공용 언어 런타임의 컨텍스트 안에서만 의미가 있습니다.

문 람다는 다음과 같이 중괄호 안에 문을 지정한다는 점을 제외하면 식 람다와 비슷합니다.

(input parameters) => {statement;}

문 람다의 본문에 지정할 수 있는 문의 개수에는 제한이 없지만 일반적으로 2-3개 정도만 지정합니다.

delegate void TestDelegate(string s);
…
TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
myDel("Hello");

무명 메서드와 마찬가지로 문 람다는 식 트리를 만드는 데 사용할 수 없습니다.

async 및 await 키워드를 사용하여 비동기 처리를 통합하는 람다 식과 문을 쉽게 만들 수 있습니다. 예를 들어 다음 Windows Forms 예제에는 비동기 메서드 ExampleMethodAsync를 호출하고 기다리는 이벤트 처리기가 포함되어 있습니다.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        // ExampleMethodAsync returns a Task.
        await ExampleMethodAsync();
        textBox1.Text += "\r\nControl returned to Click event handler.\r\n";
    }

    async Task ExampleMethodAsync()
    {
        // The following line simulates a task-returning asynchronous process.
        await Task.Delay(1000);
    }
}

비동기 람다를 사용하여 동일한 이벤트 처리기를 추가할 수 있습니다. 이 처리기를 추가하려면 다음 예제에 표시된 것처럼 람다 매개 변수 목록에 async 한정자를 추가합니다.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        button1.Click += async (sender, e) =>
        {
            // ExampleMethodAsync returns a Task.
            await ExampleMethodAsync();
            textBox1.Text += "\r\nControl returned to Click event handler.\r\n";
        };
    }

    async Task ExampleMethodAsync()
    {
        // The following line simulates a task-returning asynchronous process.
        await Task.Delay(1000);
    }
}

비동기 메서드를 만들고 사용하는 방법에 대한 자세한 내용은 Async 및 Await를 사용한 비동기 프로그래밍(C# 및 Visual Basic)을 참조하십시오.

대부분의 표준 쿼리 연산자에는 형식이 제네릭 대리자의 Func<T, TResult> 패밀리 중 하나인 입력 매개 변수를 사용합니다. 이러한 대리자는 형식 매개 변수를 사용하여 입력 매개 변수의 수와 형식 및 대리자의 반환 형식을 정의합니다. Func 대리자는 소스 데이터 집합에 있는 각 요소에 적용할 사용자 정의 식을 캡슐화하는 데 매우 유용합니다. 다음 대리자 형식을 예로 들 수 있습니다.

public delegate TResult Func<TArg0, TResult>(TArg0 arg0)

이 경우 대리자를 Func<int,bool> myFunc로 인스턴스화할 수 있습니다. 여기서 int는 입력 매개 변수이고, bool은 반환 값입니다. 반환 값은 항상 마지막 형식 매개 변수에 지정됩니다. Func<int, string, bool>는 두 입력 매개 변수로 int 형식과 string 형식을 사용하여 대리자를 정의하고 bool 형식을 반환합니다. 다음 Func 대리자를 호출하면 입력 매개 변수가 5인지 여부를 나타내는 true 또는 false가 반환됩니다.

Func<int, bool> myFunc = x => x == 5;
bool result = myFunc(4); // returns false of course

System.Linq.Queryable에 정의되어 있는 표준 쿼리 연산자의 경우와 같이 인수 형식이 Expression<Func>인 경우에도 람다 식을 사용할 수 있습니다.Expression<Func> 인수를 지정하면 식 트리에 람다 식이 컴파일됩니다.

다음 코드에서는 표준 쿼리 연산자인 Count 메서드를 보여 줍니다.

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);

컴파일러에서 입력 매개 변수의 형식을 유추하거나 사용자가 형식을 명시적으로 지정할 수 있습니다. 이 람다 식은 2로 나누었을 때 나머지가 1인 정수(n)의 수를 계산합니다.

다음 코드 줄은 숫자 시퀀스에서 조건을 만족하지 않는 첫 번째 숫자가 "9"이기 때문에 numbers 배열에서 "9" 왼쪽에 있는 모든 요소가 포함된 시퀀스를 생성합니다.

var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);

이 예제에서는 괄호로 묶어 입력 매개 변수를 여러 개 지정하는 방법을 보여 줍니다. 이 메서드는 값이 해당 위치보다 작은 숫자를 발견할 때까지 숫자 배열의 모든 요소를 반환합니다. 여기서 람다 연산자(=>)를 크거나 같음 연산자(>=)와 혼동하면 안 됩니다.

var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);

컴파일러에서는 람다 식 본문, 매개 변수의 대리자 형식 및 C# 언어 사양에 설명되어 있는 기타 요소를 기준으로 형식을 유추할 수 있기 때문에 대부분의 경우에는 람다 식을 작성할 때 입력 매개 변수의 형식을 지정하지 않아도 됩니다. 대부분의 표준 쿼리 연산자에서 첫 번째 입력 형식은 소스 시퀀스 요소의 형식입니다. 따라서 IEnumerable<Customer>를 쿼리할 경우 입력 변수가 Customer 개체로 유추됩니다. 이는 이 개체의 메서드와 속성에 액세스할 수 있음을 의미합니다.

customers.Where(c => c.City == "London");

람다 식에는 다음과 같은 일반적인 규칙이 적용됩니다.

  • 람다 식과 대리자 형식에 포함된 매개 변수 수가 같아야 합니다.

  • 람다 식의 각 입력 매개 변수는 해당되는 대리자 매개 변수로 암시적으로 변환될 수 있어야 합니다.

  • 람다 식의 반환 값(있는 경우)은 대리자의 반환 형식으로 암시적으로 변환될 수 있어야 합니다.

공용 형식 시스템에는 "람다 식"이라는 개념이 기본적으로 포함되어 있지 않기 때문에 람다 식 자체에는 형식이 없습니다. 그러나 람다 식의 "형식"을 비공식적으로 언급해야 할 경우도 있는데 이 경우 형식은 대리자 형식 또는 람다 식이 변환되는 Expression 형식을 의미합니다.

람다 식은 람다 함수를 정의하는 메서드 범위 내에 있거나 람다 식을 포함하는 형식 범위 내에 있는 외부 변수(무명 메서드(C# 프로그래밍 가이드) 참조)를 참조할 수 있습니다. 이러한 방식으로 캡처되는 변수는 변수가 범위를 벗어나 가비지 수집되는 경우에도 람다 식에 사용할 수 있도록 저장됩니다. 외부 변수는 명확하게 할당해야만 람다 식에 사용할 수 있습니다. 다음 예제에서는 이러한 규칙을 보여 줍니다.

delegate bool D();
delegate bool D2(int i);

class Test
{
    D del;
    D2 del2;
    public void TestMethod(int input)
    {
        int j = 0;
        // Initialize the delegates with lambda expressions.
        // Note access to 2 outer variables.
        // del will be invoked within this method.
        del = () => { j = 10;  return j > input; };

        // del2 will be invoked after TestMethod goes out of scope.
        del2 = (x) => {return x == j; };
      
        // Demonstrate value of j:
        // Output: j = 0 
        // The delegate has not been invoked yet.
        Console.WriteLine("j = {0}", j);        // Invoke the delegate.
        bool boolResult = del();

        // Output: j = 10 b = True
        Console.WriteLine("j = {0}. b = {1}", j, boolResult);
    }

    static void Main()
    {
        Test test = new Test();
        test.TestMethod(5);

        // Prove that del2 still has a copy of
        // local variable j from TestMethod.
        bool result = test.del2(10);

        // Output: True
        Console.WriteLine(result);
           
        Console.ReadKey();
    }
}

람다 식의 변수 범위에는 다음과 같은 규칙이 적용됩니다.

  • 캡처된 변수는 해당 변수를 참조하는 대리자가 가비지 수집 대상이 될 때까지 가비지 수집되지 않습니다.

  • 람다 식에 사용된 변수는 외부 메서드에 표시되지 않습니다.

  • 람다 식은 바깥쪽 메서드에서 ref 또는 out 매개 변수를 직접 캡처할 수 없습니다.

  • 람다 식의 return 문에 의해서는 바깥쪽 메서드가 반환되지 않습니다.

  • 점프문의 대상이 블록 외부에 있는 경우 람다 식에 람다 함수 내에 있는 goto 문, break 문 또는 continue 문을 포함할 수 없습니다. 대상이 블록 내에 있는 경우 람다 함수 블록 외부에 점프문을 사용해도 오류가 발생합니다.

자세한 내용은 C# 언어 사양을 참조하십시오. 이 언어 사양은 C# 구문 및 사용법에 대한 신뢰할 수 있는 소스입니다.


반응형

'Programming > C#' 카테고리의 다른 글

Calendar Class[MSDN]  (0) 2014.09.01
C# 강의  (0) 2014.08.29
Get Dictionary key by using the dictionary value  (0) 2014.08.12
[C#] How to get/set using index for a Dictionary?  (0) 2014.08.06
NTP 서버에서 시간 가져오기(SNTP)  (0) 2014.07.14
Posted by blueasa
, |
public static class Extensions
{
    public static bool TryGetKey<K, V>(this IDictionary<K, V> instance, V value, out K key)
    {
        foreach (var entry in instance)
        {
            if (!entry.Value.Equals(value))
            {
                continue;
            }
            key = entry.Key;
            return true;
        }
        key = default(K);
        return false;
    }
}

the usage is also so simple

int key = 0;
if (myDictionary.TryGetKey("twitter", out key))
{
    // successfully got the key :)
}



Link : http://stackoverflow.com/questions/4001908/get-dictionary-key-by-using-the-dictionary-value



[참조] https://www.dotnetperls.com/extension

반응형

'Programming > C#' 카테고리의 다른 글

C# 강의  (0) 2014.08.29
람다 식  (0) 2014.08.29
[C#] How to get/set using index for a Dictionary?  (0) 2014.08.06
NTP 서버에서 시간 가져오기(SNTP)  (0) 2014.07.14
C# 외부 프로그램 종료하기  (0) 2014.05.20
Posted by blueasa
, |
public class YourClass
{
    private readonly IDictionary<string, string> _yourDictionary = new Dictionary<string, string>();

    public string this[string key]
    {
        // returns value if exists
        get { return _yourDictionary[key]; }

        // updates if exists, adds if doesn't exist
        set { _yourDictionary[key] = value; }
    }
}





class SampleCollection<T>
{
    // Declare an array to store the data elements. 
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code 
    // to use [] notation on the class instance itself. 
    // (See line 2 of code in Main below.)         
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets 
            // the corresponding element from the internal array. 
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer. 
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
// Output: 
// Hello, World.


Link : http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

반응형

'Programming > C#' 카테고리의 다른 글

람다 식  (0) 2014.08.29
Get Dictionary key by using the dictionary value  (0) 2014.08.12
NTP 서버에서 시간 가져오기(SNTP)  (0) 2014.07.14
C# 외부 프로그램 종료하기  (0) 2014.05.20
C# Keywords  (0) 2014.05.13
Posted by blueasa
, |

[추가]

Google NTP 주소 : time.google.com

[링크] https://developers.google.com/time/



C# - Simple Network Time (NTP) Protocol Client

SNTPClient.cs






Network Time Protocol (NTP) is a protocol for synchronizing the clocks of computer systems over packet-switched, variable-latency data networks. NTP uses UDP on port 123 as its transport layer. It is designed particularly to resist the effects of variable latency by using a jitter buffer. NTP also refers to a reference software implementation that is distributed by the NTP Public Services Project.

NTP is one of the oldest Internet protocols still in use (since before 1985). NTP was originally designed by Dave Mills of the University of Delaware, who still maintains it, along with a team of volunteers.

NTP is not related to the simpler DAYTIME (RFC 867) and TIME (RFC 868) protocols.

 

위키에서 가져옴-_-

 

경로 : http://en.wikipedia.org/wiki/Network_Time_Protocol

 

 

서버 따위에서 시간을 맞추기 위해서 사용하는 프로토콜이고 이런 시간 정보를 제공하는 서버를 타임 서버라고 많이들 이야길 하죠..

 

아래  ITS 는 아주 간단하게 구현되고 사용할 수 있지만 NTP 는 좀 까다롭습니다. -_-

 

그래서 괜히 어설프게 문서 만들고 예제 만들다간 욕 처먹을거 같아서 -.- 클래스 퍼온거 올려봅니다.

 

(원래는 간단하게 -_- 만들고 있었는데 제대로 된 소스를 발견해서 쪽팔려서 지움..;; -_- )

 

 

일단 아래는 활용 예제와 결과물입니다. 

 

namespace InternetTime

{

    using System;

 

    public class Synchronizer

    {

        public Synchronizer()

        {

        }

 

        public static int Main(string[] args)

        {

            SNTPClient client;

            try

            {

                client = new SNTPClient("time.google.com"); // Google NTP 서버 주소 추가

                //client = new SNTPClient("time.nuri.net");    // 참조할 NTP 서버 주소

                client.Connect(false);

            }

            catch (Exception e)

            {

                Console.WriteLine("ERROR: {0}", e.Message);

                return -1;

            }

 

            Console.Write(client.ToString());

            return 0;

        }

    }

}



출처 : http://www.devpia.com/Maeul/Contents/Detail.aspx?BoardID=18&MAEULNO=8&no=1770&page=11




반응형

'Programming > C#' 카테고리의 다른 글

Get Dictionary key by using the dictionary value  (0) 2014.08.12
[C#] How to get/set using index for a Dictionary?  (0) 2014.08.06
C# 외부 프로그램 종료하기  (0) 2014.05.20
C# Keywords  (0) 2014.05.13
Standard Numeric Format Strings  (0) 2014.05.13
Posted by blueasa
, |

링크 : http://www.pressblog.co.kr/linkblog/471319

반응형

'Programming > C#' 카테고리의 다른 글

[C#] How to get/set using index for a Dictionary?  (0) 2014.08.06
NTP 서버에서 시간 가져오기(SNTP)  (0) 2014.07.14
C# Keywords  (0) 2014.05.13
Standard Numeric Format Strings  (0) 2014.05.13
숫자 3자리마다 콤마(,) 찍기  (0) 2014.05.13
Posted by blueasa
, |

C# Keywords

Programming/C# / 2014. 5. 13. 15:37

출처 : http://msdn.microsoft.com/en-us/library/x53a06bb.aspx


C# Keywords

Visual Studio 2013
14 out of 17 rated this helpful Rate this topic

Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier but if is not because if is a keyword.

The first table in this topic lists keywords that are reserved identifiers in any part of a C# program. The second table in this topic lists the contextual keywords in C#. Contextual keywords have special meaning only in a limited program context and can be used as identifiers outside that context. Generally, as new keywords are added to the C# language, they are added as contextual keywords in order to avoid breaking programs written in earlier versions.

Contextual Keywords

A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#. Some contextual keywords, such as partial and where, have special meanings in two or more contexts.



반응형
Posted by blueasa
, |

Standard Numeric Format Strings

.NET Framework 4.5
37 out of 50 rated this helpful Rate this topic

Standard numeric format strings are used to format common numeric types. A standard numeric format string takes the form Axx, where A is an alphabetic character called the format specifier, and xx is an optional integer called the precision specifier. The precision specifier ranges from 0 to 99 and affects the number of digits in the result. Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string. For more information, see Custom Numeric Format Strings.

Important note Important

The precision specifier controls the number of digits in the string representation of a number. It does not round the number itself. To perform a rounding operation, use the Math.CeilingMath.Floor, orMath.Round method.

Standard numeric format strings are supported by some overloads of the ToString method of all numeric types. For example, you can supply a numeric format string to the ToString(String) andToString(String, IFormatProvider) methods of the Int32 type. Standard numeric format strings are also supported by the .NET Framework composite formatting feature, which is used by some Write andWriteLine methods of the Console and StreamWriter classes, the String.Format method, and theStringBuilder.AppendFormat method.

Tip Tip

You can download the Format Utility, an application that enables you to apply format strings to either numeric or date and time values and displays the result string.

The following table describes the standard numeric format specifiers and displays sample output produced by each format specifier. See the Notes section for additional information about using standard numeric format strings, and the Example section for a comprehensive illustration of their use.

Format specifier

Name

Description

Examples

"C" or "c"

Currency

Result: A currency value.

Supported by: All numeric types.

Precision specifier: Number of decimal digits.

Default precision specifier: Defined bySystem.Globalization.NumberFormatInfo.

More information: The Currency ("C") Format Specifier.

123.456 ("C", en-US) -> $123.46

123.456 ("C", fr-FR) -> 123,46 €

123.456 ("C", ja-JP) -> ¥123

-123.456 ("C3", en-US) -> ($123.456)

-123.456 ("C3", fr-FR) -> -123,456 €

-123.456 ("C3", ja-JP) -> -¥123.456

"D" or "d"

Decimal

Result: Integer digits with optional negative sign.

Supported by: Integral types only.

Precision specifier: Minimum number of digits.

Default precision specifier: Minimum number of digits required.

More information: The Decimal("D") Format Specifier.

1234 ("D") -> 1234

-1234 ("D6") -> -001234

"E" or "e"

Exponential (scientific)

Result: Exponential notation.

Supported by: All numeric types.

Precision specifier: Number of decimal digits.

Default precision specifier: 6.

More information: The Exponential ("E") Format Specifier.

1052.0329112756 ("E", en-US) -> 1.052033E+003

1052.0329112756 ("e", fr-FR) -> 1,052033e+003

-1052.0329112756 ("e2", en-US) -> -1.05e+003

-1052.0329112756 ("E2", fr_FR) -> -1,05E+003

"F" or "f"

Fixed-point

Result: Integral and decimal digits with optional negative sign.

Supported by: All numeric types.

Precision specifier: Number of decimal digits.

Default precision specifier: Defined bySystem.Globalization.NumberFormatInfo.

More information: The Fixed-Point ("F") Format Specifier.

1234.567 ("F", en-US) -> 1234.57

1234.567 ("F", de-DE) -> 1234,57

1234 ("F1", en-US) -> 1234.0

1234 ("F1", de-DE) -> 1234,0

-1234.56 ("F4", en-US) -> -1234.5600

-1234.56 ("F4", de-DE) -> -1234,5600

"G" or "g"

General

Result: The most compact of either fixed-point or scientific notation.

Supported by: All numeric types.

Precision specifier: Number of significant digits.

Default precision specifier: Depends on numeric type.

More information: The General ("G") Format Specifier.

-123.456 ("G", en-US) -> -123.456

123.456 ("G", sv-SE) -> -123,456

123.4546 ("G4", en-US) -> 123.5

123.4546 ("G4", sv-SE) -> 123,5

-1.234567890e-25 ("G", en-US) -> -1.23456789E-25

-1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25

"N" or "n"

Number

Result: Integral and decimal digits, group separators, and a decimal separator with optional negative sign.

Supported by: All numeric types.

Precision specifier: Desired number of decimal places.

Default precision specifier: Defined bySystem.Globalization.NumberFormatInfo.

More information: The Numeric ("N") Format Specifier.

1234.567 ("N", en-US) -> 1,234.57

1234.567 ("N", ru-RU) -> 1 234,57

1234 ("N1", en-US) -> 1,234.0

1234 ("N1", ru-RU) -> 1 234,0

-1234.56 ("N3", en-US) -> -1,234.560

-1234.56 ("N3", ru-RU) -> -1 234,560

"P" or "p"

Percent

Result: Number multiplied by 100 and displayed with a percent symbol.

Supported by: All numeric types.

Precision specifier: Desired number of decimal places.

Default precision specifier: Defined bySystem.Globalization.NumberFormatInfo.

More information: The Percent ("P") Format Specifier.

1 ("P", en-US) -> 100.00 %

1 ("P", fr-FR) -> 100,00 %

-0.39678 ("P1", en-US) -> -39.7 %

-0.39678 ("P1", fr-FR) -> -39,7 %

"R" or "r"

Round-trip

Result: A string that can round-trip to an identical number.

Supported by: SingleDouble, and BigInteger.

Precision specifier: Ignored.

More information: The Round-trip ("R") Format Specifier.

123456789.12345678 ("R") -> 123456789.12345678

-1234567890.12345678 ("R") -> -1234567890.1234567

"X" or "x"

Hexadecimal

Result: A hexadecimal string.

Supported by: Integral types only.

Precision specifier: Number of digits in the result string.

More information: The HexaDecimal ("X") Format Specifier.

255 ("X") -> FF

-1 ("x") -> ff

255 ("x4") -> 00ff

-1 ("X4") -> 00FF

Any other single character

Unknown specifier

Result: Throws a FormatException at run time.

Using Standard Numeric Format Strings

A standard numeric format string can be used to define the formatting of a numeric value in one of two ways:

  • It can be passed to an overload of the ToString method that has a format parameter. The following example formats a numeric value as a currency string in the current (in this case, the en-US) culture.

    decimal value = 123.456m;
    Console.WriteLine(value.ToString("C2"));
    // Displays $123.46
    
  • It can be supplied as the formatString parameter in a format item used with such methods asString.FormatConsole.WriteLine, and StringBuilder.AppendFormat. For more information, seeComposite Formatting. The following example uses a format item to insert a currency value in a string.

    decimal value = 123.456m;
    Console.WriteLine("Your account balance is {0:C2}.", value);
    // Displays "Your account balance is $123.46."
    

The following sections provide detailed information about each of the standard numeric format strings.

The Currency ("C") Format Specifier

The "C" (or currency) format specifier converts a number to a string that represents a currency amount. The precision specifier indicates the desired number of decimal places in the result string. If the precision specifier is omitted, the default precision is defined by theNumberFormatInfo.CurrencyDecimalDigits property.

If the value to be formatted has more than the specified or default number of decimal places, the fractional value is rounded in the result string. If the value to the right of the number of specified decimal places is 5 or greater, the last digit in the result string is rounded away from zero.

The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo property

Description

CurrencyPositivePattern

Defines the placement of the currency symbol for positive values.

CurrencyNegativePattern

Defines the placement of the currency symbol for negative values, and specifies whether the negative sign is represented by parentheses or the NegativeSign property.

NegativeSign

Defines the negative sign used if CurrencyNegativePattern indicates that parentheses are not used.

CurrencySymbol

Defines the currency symbol.

CurrencyDecimalDigits

Defines the default number of decimal digits in a currency value. This value can be overridden by using the precision specifier.

CurrencyDecimalSeparator

Defines the string that separates integral and decimal digits.

CurrencyGroupSeparator

Defines the string that separates groups of integral numbers.

CurrencyGroupSizes

Defines the number of integer digits that appear in a group.

The following example formats a Double value with the currency format specifier.

double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", 
                  CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose 
// current culture is English (United States): 
//       $12,345.68 
//       $12,345.679 
//       kr 12.345,679

Back to table

The Decimal ("D") Format Specifier

The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. This format is supported only for integral types.

The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. If no precision specifier is specified, the default is the minimum value required to represent the integer without leading zeros.

The result string is affected by the formatting information of the current NumberFormatInfo object. As the following table shows, a single property affects the formatting of the result string.

NumberFormatInfo property

Description

NegativeSign

Defines the string that indicates that a number is negative.

The following example formats an Int32 value with the decimal format specifier.

int value; 

value = 12345;
Console.WriteLine(value.ToString("D"));
// Displays 12345
Console.WriteLine(value.ToString("D8"));
// Displays 00012345 

value = -12345;
Console.WriteLine(value.ToString("D"));
// Displays -12345
Console.WriteLine(value.ToString("D8"));
// Displays -00012345

Back to table

The Exponential ("E") Format Specifier

The exponential ("E") format specifier converts a number to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative. Exactly one digit always precedes the decimal point.

The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, a default of six digits after the decimal point is used.

The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required.

The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo property

Description

NegativeSign

Defines the string that indicates that a number is negative for both the coefficient and exponent.

NumberDecimalSeparator

Defines the string that separates the integral digit from decimal digits in the coefficient.

PositiveSign

Defines the string that indicates that an exponent is positive.

The following example formats a Double value with the exponential format specifier.

double value = 12345.6789;
Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture));
// Displays 1.234568E+004

Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture));
// Displays 1.2345678900E+004

Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture));
// Displays 1.2346e+004

Console.WriteLine(value.ToString("E", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 1,234568E+004

Back to table

The Fixed-Point ("F") Format Specifier

The fixed-point ("F) format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative.

The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the current NumberFormatInfo.NumberDecimalDigits property supplies the numeric precision.

The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the properties of the NumberFormatInfo object that control the formatting of the result string.

NumberFormatInfo property

Description

NegativeSign

Defines the string that indicates that a number is negative.

NumberDecimalSeparator

Defines the string that separates integral digits from decimal digits.

NumberDecimalDigits

Defines the default number of decimal digits. This value can be overridden by using the precision specifier.

The following example formats a Double and an Int32 value with the fixed-point format specifier.

int integerNumber;
integerNumber = 17843;
Console.WriteLine(integerNumber.ToString("F", 
                  CultureInfo.InvariantCulture));
// Displays 17843.00

integerNumber = -29541;
Console.WriteLine(integerNumber.ToString("F3", 
                  CultureInfo.InvariantCulture));
// Displays -29541.000 

double doubleNumber;
doubleNumber = 18934.1879;
Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture));
// Displays 18934.19

Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture));
// Displays 18934

doubleNumber = -1898300.1987;
Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture));  
// Displays -1898300.2

Console.WriteLine(doubleNumber.ToString("F3", 
                  CultureInfo.CreateSpecificCulture("es-ES")));
// Displays -1898300,199                        

Back to table

The General ("G") Format Specifier

The general ("G") format specifier converts a number to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present. The precision specifier defines the maximum number of significant digits that can appear in the result string. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated in the following table.

Numeric type

Default precision

Byte or SByte

3 digits

Int16 or UInt16

5 digits

Int32 or UInt32

10 digits

Int64

19 digits

UInt64

20 digits

BigInteger

50 digits

Single

7 digits

Double

15 digits

Decimal

29 digits

Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and less than the precision specifier; otherwise, scientific notation is used. The result contains a decimal point if required, and trailing zeros after the decimal point are omitted. If the precision specifier is present and the number of significant digits in the result exceeds the specified precision, the excess trailing digits are removed by rounding.

However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved.

If scientific notation is used, the exponent in the result is prefixed with "E" if the format specifier is "G", or "e" if the format specifier is "g". The exponent contains a minimum of two digits. This differs from the format for scientific notation that is produced by the exponential format specifier, which includes a minimum of three digits in the exponent.

The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo property

Description

NegativeSign

Defines the string that indicates that a number is negative.

NumberDecimalSeparator

Defines the string that separates integral digits from decimal digits.

PositiveSign

Defines the string that indicates that an exponent is positive.

The following example formats assorted floating-point values with the general format specifier.

double number;

number = 12345.6789;      
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays  12345.6789
Console.WriteLine(number.ToString("G", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 12345,6789

Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));
// Displays 12345.68 

number = .0000023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 2.3E-06       
Console.WriteLine(number.ToString("G", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 2,3E-06

number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023

number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03

number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416    

Back to table

The Numeric ("N") Format Specifier

The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." indicates a decimal point symbol. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, the number of decimal places is defined by the current NumberFormatInfo.NumberDecimalDigits property.

The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo property

Description

NegativeSign

Defines the string that indicates that a number is negative.

NumberNegativePattern

Defines the format of negative values, and specifies whether the negative sign is represented by parentheses or the NegativeSignproperty.

NumberGroupSizes

Defines the number of integral digits that appear between group separators.

NumberGroupSeparator

Defines the string that separates groups of integral numbers.

NumberDecimalSeparator

Defines the string that separates integral and decimal digits.

NumberDecimalDigits

Defines the default number of decimal digits. This value can be overridden by using a precision specifier.

The following example formats assorted floating-point values with the number format specifier.

double dblValue = -12445.6789;
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture));
// Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1", 
                  CultureInfo.CreateSpecificCulture("sv-SE")));
// Displays -12 445,7 

int intValue = 123456789;
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture));
// Displays 123,456,789.0 

Back to table

The Percent ("P") Format Specifier

The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision supplied by the currentPercentDecimalDigits property is used.

The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo property

Description

PercentPositivePattern

Defines the placement of the percent symbol for positive values.

PercentNegativePattern

Defines the placement of the percent symbol and the negative symbol for negative values.

NegativeSign

Defines the string that indicates that a number is negative.

PercentSymbol

Defines the percent symbol.

PercentDecimalDigits

Defines the default number of decimal digits in a percentage value. This value can be overridden by using the precision specifier.

PercentDecimalSeparator

Defines the string that separates integral and decimal digits.

PercentGroupSeparator

Defines the string that separates groups of integral numbers.

PercentGroupSizes

Defines the number of integer digits that appear in a group.

The following example formats floating-point values with the percent format specifier.

double number = .2468013;
Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture));
// Displays 24.68 %
Console.WriteLine(number.ToString("P", 
                  CultureInfo.CreateSpecificCulture("hr-HR")));
// Displays 24,68%     
Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture));
// Displays 24.7 %

Back to table

The Round-trip ("R") Format Specifier

The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value. This format is supported only for the SingleDouble, and BigInteger types.

When a BigInteger value is formatted using this specifier, its string representation contains all the significant digits in the BigInteger value. When a Single or Double value is formatted using this specifier, it is first tested using the general format, with 15 digits of precision for a Double and 7 digits of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. If the value is not successfully parsed back to the same numeric value, it is formatted using 17 digits of precision for a Double and 9 digits of precision for aSingle.

Although you can include a precision specifier, it is ignored. Round trips are given precedence over precision when using this specifier.

The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo property

Description

NegativeSign

Defines the string that indicates that a number is negative.

NumberDecimalSeparator

Defines the string that separates integral digits from decimal digits.

PositiveSign

Defines the string that indicates that an exponent is positive.

The following example formats Double values with the round-trip format specifier.

double value;

value = Math.PI;
Console.WriteLine(value.ToString("r"));
// Displays 3.1415926535897931
Console.WriteLine(value.ToString("r", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 3,1415926535897931 
value = 1.623e-21;
Console.WriteLine(value.ToString("r"));
// Displays 1.623E-21

Back to table

The Hexadecimal ("X") Format Specifier

The hexadecimal ("X") format specifier converts a number to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for hexadecimal digits that are greater than 9. For example, use "X" to produce "ABCDEF", and "x" to produce "abcdef". This format is supported only for integral types.

The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.

The result string is not affected by the formatting information of the current NumberFormatInfoobject.

The following example formats Int32 values with the hexadecimal format specifier.

int value; 

value = 0x2045e;
Console.WriteLine(value.ToString("x"));
// Displays 2045e
Console.WriteLine(value.ToString("X"));
// Displays 2045E
Console.WriteLine(value.ToString("X8"));
// Displays 0002045E 

value = 123456789;
Console.WriteLine(value.ToString("X"));
// Displays 75BCD15
Console.WriteLine(value.ToString("X2"));
// Displays 75BCD15

Back to table

Notes

Control Panel Settings

The settings in the Regional and Language Options item in Control Panel influence the result string produced by a formatting operation. Those settings are used to initialize theNumberFormatInfo object associated with the current thread culture, which provides values used to govern formatting. Computers that use different settings generate different result strings.

In addition, if the CultureInfo.CultureInfo(String) constructor is used to instantiate a new CultureInfoobject that represents the same culture as the current system culture, any customizations established by the Regional and Language Options item in Control Panel will be applied to the new CultureInfo object. You can use the CultureInfo.CultureInfo(String, Boolean) constructor to create a CultureInfo object that does not reflect a system's customizations.

NumberFormatInfo Properties

Formatting is influenced by the properties of the current NumberFormatInfo object, which is provided implicitly by the current thread culture or explicitly by the IFormatProvider parameter of the method that invokes formatting. Specify a NumberFormatInfo or CultureInfo object for that parameter.

Note Note

For information about customizing the patterns or strings used in formatting numeric values, see the NumberFormatInfo class topic.

Integral and Floating-Point Numeric Types

Some descriptions of standard numeric format specifiers refer to integral or floating-point numeric types. The integral numeric types are ByteSByteInt16Int32Int64UInt16UInt32UInt64, andBigInteger. The floating-point numeric types are DecimalSingle, and Double.

Floating-Point Infinities and NaN

Regardless of the format string, if the value of a Single or Double floating-point type is positive infinity, negative infinity, or not a number (NaN), the formatted string is the value of the respectivePositiveInfinitySymbolNegativeInfinitySymbol, or NaNSymbol property that is specified by the currently applicable NumberFormatInfo object.

Example

The following example formats an integral and a floating-point numeric value using the en-US culture and all the standard numeric format specifiers. This example uses two particular numeric types (Double and Int32), but would yield similar results for any of the other numeric base types (Byte,SByteInt16Int32Int64UInt16UInt32UInt64BigIntegerDecimal, and Single).

using System;
using System.Globalization;
using System.Threading;

public class NumericFormats
{
   public static void Main()
   {
      // Display string representations of numbers for en-us culture
      CultureInfo ci = new CultureInfo("en-us");

      // Output floating point values 
      double floating = 10761.937554;
      Console.WriteLine("C: {0}", 
              floating.ToString("C", ci));           // Displays "C: $10,761.94"
      Console.WriteLine("E: {0}", 
              floating.ToString("E03", ci));         // Displays "E: 1.076E+004"
      Console.WriteLine("F: {0}", 
              floating.ToString("F04", ci));         // Displays "F: 10761.9376"         
      Console.WriteLine("G: {0}",  
              floating.ToString("G", ci));           // Displays "G: 10761.937554"
      Console.WriteLine("N: {0}", 
              floating.ToString("N03", ci));         // Displays "N: 10,761.938"
      Console.WriteLine("P: {0}", 
              (floating/10000).ToString("P02", ci)); // Displays "P: 107.62 %"
      Console.WriteLine("R: {0}", 
              floating.ToString("R", ci));           // Displays "R: 10761.937554"            
      Console.WriteLine();

      // Output integral values 
      int integral = 8395;
      Console.WriteLine("C: {0}", 
              integral.ToString("C", ci));           // Displays "C: $8,395.00"
      Console.WriteLine("D: {0}", 
              integral.ToString("D6", ci));          // Displays "D: 008395" 
      Console.WriteLine("E: {0}", 
              integral.ToString("E03", ci));         // Displays "E: 8.395E+003"
      Console.WriteLine("F: {0}", 
              integral.ToString("F01", ci));         // Displays "F: 8395.0"    
      Console.WriteLine("G: {0}",  
              integral.ToString("G", ci));           // Displays "G: 8395"
      Console.WriteLine("N: {0}", 
              integral.ToString("N01", ci));         // Displays "N: 8,395.0"
      Console.WriteLine("P: {0}", 
              (integral/10000.0).ToString("P02", ci)); // Displays "P: 83.95 %"
      Console.WriteLine("X: 0x{0}", 
              integral.ToString("X", ci));           // Displays "X: 0x20CB"
      Console.WriteLine();
   }
}


출처 : http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

반응형

'Programming > C#' 카테고리의 다른 글

C# 외부 프로그램 종료하기  (0) 2014.05.20
C# Keywords  (0) 2014.05.13
숫자 3자리마다 콤마(,) 찍기  (0) 2014.05.13
플래그 데이터와 이진 연산  (0) 2014.04.04
How to create Excel file in C#(Source)  (0) 2014.03.26
Posted by blueasa
, |