4월, 2015의 게시물 표시

C#의 언어적 특징

언어적 특징 자바와 유사하나 자바와 달리 불안전 코드(unsafe code)와 같은 기술을 통하여 플랫폼 간 상호 운용성을 중시. 상 C#의 기본 자료형은 닷넷의 객체 모델을 따르고 있고,  런타임 차원에서의 메모리 수거(garbage collection)가 되며  또한 클래스, 인터페이스, 위임, 예외와 같이 객체 지향 언어로서 가져야 할 모든 요소들이 포함, 하 Case Sensitive, C#은 Strong-Type Language(변수, 함수원형 선언해야) 중 변수, 연산자, 제어문은 거의 C/C++과 유사, 하 클래스, 객체지향 방식은 델파이와 매우 유사, 중 콤포넌트명은 소문자로 시작해야 인식: 중 button.Location = new Point(100, 30); statusBar1.Text="good"; Comment:  // 한줄, /* */ 블럭, /// XML 하 C#은 C/C++과는 달리 헤더파일이 없다. 하 모든 C# 애플리케이션은 그 클래스들 중 하나에 반드시 Main 메소드를 포함해야 한다. 상 C/C++과 달리 .NET에서의 char은 유니코드 , 상 C#은 C++보다 형 안전성에 대하여 더 관대하다. 중! 이 말은 형 안정성을 보장할 수 없다는 것도 동시에 뜻한다.  System.Object 클래스가 모든 클래스의 선조 클래스이기 때문에 이러한 관대함이 가능하게 되었다.  배열은 자바와 유사, C/C++에서는 배열의 인덱스에 대한 존재여부의 체크가 없었지만 C#의 경우에는 에러를 발생한다. 상 골뱅이로 Escape Code 회피 문자열 생성  중 개발가능 플랫폼  하 fixed 블록을 이용하여 힙에 데이터를 고정할 수 있다. 상
이미지
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; using System.Threading; namespace WindowsFormsApplication7 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         private void button1_Click(object sender, EventArgs e)         {             Stopwatch st1=new Stopwatch();             st1.Start();             for (int x=0;x<9999 ;x++ )             {                 for (int y=0; y<999...

CS는 C++ 더하기 Java가 아니다

C# == [C++] + [Java] 는 아니다 Turbo Pascal → Delphi(Object Pascal) → C#(C Sharp) 이다. 종종 「C# 는 C++ 와 Java 의 장점을 섞은것」이라고 말합니다. 그러나, C/C++, Java, Delphi, VB 를 섭렵해오고 있는 나에게 있어서, 이것에는 동의 할수 없습니다. C# 는 C 레벨의 문법을 근거로 해 C++ 의 일부를 답습하고 있는 부분은 있습니다만, C++ 의 언어 사양으로부터, 분명하게 피하고 있는 부분 (가령「다중 상속」이나「unsafe 포인터」등)도 있습니다. 이 부분이 Java 에 해당된다면, C++ 를 거론하는 의미가 그다지 없어보입니다. 전체의 특성으로 선택한다면, 나는, Delphi + Java 가 아닐까 생각합니다. Delphi 를 해보면 알겠지만, 컨트롤 측면, 특히 이벤트 측면이 매우 닮았습니다. 조금 어렵겠지만 코드로 설명해 보자면, //Delphi ————————————- procedure TForm1.Button1Click(Sender: TObject); var i: integer begin for i := 0 to 10 do begin // TODO : 여러 가지 end; end; TForm1 ? Sender 근처는, 무엇인가 그것 같지요? (^^) 그래그래, Delphi 에서는, 클래스를 나타내기 위한 프리픽스에 「T」를 사용합니다만, C# 나 VB.NET 로 생성되는 XML 문서로의 클래스도 「T:클래스 패스」라고 쓰는군요. 그런데, 이야기를 되돌립니다.(;^-^) 이상하다고 생각하는 이유의 하나로서 같은 부류의 언어인 VB.NET 의 식이 성립되지 않는다고 하는 것에 있습니다. C# == [C++] + [Java] 로 해 버리면, VB.NET == 의 우변이 이상해지지 않겠습니까? (;^-^) 쓴다면, VB.NET == [VB] + [Java] 입니까? 아니, 이것이라면 구문 레벨이라고 하는 의미에 지나지 않게 됩니다. 프로그램의 짜는 방법이나 이벤트의 ...

RAD 개발 철칙

1. 폼에 중요한 정보를 보관하지 말라. 이말인즉, 중요한 정보를 폼 디자인시 속성값으로 저장하지 말라는 것이다. 다시 말해서, 속성창으로 중요한 정보를 입력하지 말라는 것이다. 폼에 놓여진 모든 콤포넌트와 폼 자체의 속성값들은 모두 리소스 형태로 최종 실행 파일에 포함된다. 문제는 아주 간단한 방법으로도 이 폼 리소스 정보를 꺼집어 낼수 있다는 것이다. 그러므로, 보안이 필요한 중요한 정보를 절대로 속성창으로 입력하지 말라. 특히 데이타베이스 커넥션에서 디비와 접속하는데 필요한 userid, password 등은 절대로 폼에 저장하면 안된다. 이런 정보들은 암호화하여 코딩으로 설정하던가, 아니면 클라이언트에 이런 로그인 정보를 전혀 실행파일에 보관할 필요가 없도록 3티어 방식으로 작성하라. 폼 리소스의 보안 취약성은 어떤 경우 심각한 문제를 야기하기도 하는데, 폼 리소스를 암호화하여 실행파일에 포함하는 방법도 있다. citadel 이란 콤포넌트가 이런 기능을 제공하니 참고하기 바란다. 2. 간단한 기능을 가진 콤포넌트를 과도하게 자주 만들지 말라. 윈도우에서 DLL Nightmare 란 단어를 들어봤을 것이다. 이는 수많은 프로그램을 윈도우에 설치하면서 발생하는 DLL들간의 간섭현상을 말한다. 마찬가지로 델파이에는 Component Hell 이란 단어가 있다. 이는 수많은 콤포넌트를 델파이 IDE에 설치하면서 발생하는 여러 부작용을 말한다. 현존 개발 툴 중에서, 스스로의 언어로 자신의 기능을 확장하는 툴을 만들고, 콤포넌트를 만드는 개발툴은 드물다. C++ 개발툴을 제외하고는 비베, 파워빌더 등 대부분이 콤포넌트나 기능 확장툴을 외부언어인 C나 C++에 의존한다. 반면 델파이는 오브젝트 파스칼로 확장툴, 콤포넌트 모두를 만들 수 있다. 사실 델파이만큼 콤포넌트 만들기 쉬운 툴도 잘 없다.(물론, 예외적이지만, 시샵은 콤포넌트 만드는 것이 델파이보다 더 쉽다). 문제는 델파이로 콤포넌트 만들기가 쉽다는 것 때문에, 많은 델 개발자들이 콤포넌트 작성을 필요...

C샵엔 있으나 델파이엔 없는것들

C샵엔 있으나 델파이엔 없는것들 Features C# has that Delphi doesn't ================================== 1) foreach 2) operators using, lock, checked and unchecked 3) block scoped variables 4) case statements with strings 5) assembly internal classes 6) namespaces can span code units 7) implicit array dimensioning: int[] a = new int{1,2,3}; 8) ternary operator ( ? : ) 9) can use classes from namespaces without importing the whole namespace 10) circular references are possible 11) try..catch..finally 12) assignment operators (+=, ++, -=, etc) 13) multi-file assemblies 14) You don't need to distribute Borland.Delphi.dll 15) Compiler warnings can be emitted if you omit XML documentation Features Delphi has that C# doesn't ================================== 1) sub-range types 2) enums and sets are first-class types 3) class type support 4) virtual constructors 5) virtual class methods 6) nested procedures 7) non-default index properties 8) can defines constant arrays and records 9) resou...

mcs로 컴파일하고 mono로 맥바이너리화

Using Mono on MacOS X At this point, you must use Mono from the command line, the usual set of commands that are available on other ports of Mono are available. To build applications you can use "mcs", to run then you can use mono. From a Terminal shell, you can try it out: $ vi hello.cs  $ mcs hello.cs $ mono hello.exe Hello, World $

회전/ Format32bppArgb/ GraphicsPath/ AddRectAngle/ Matrix()/ Rotate/ GetBounds

이미지
회전/ Format32bppArgb/ GraphicsPath/ AddRectAngle/ Matrix()/ Rotate/ GetBounds using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace Rotation { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public static Bitmap BitmapRotate(Bitmap bmp, float angle, Color bkColor) { int w = bmp.Width + 2; int h = bmp.Height + 2; PixelFormat pf; if (bkColor == Color.Transparent) pf = PixelFormat.Format32bppArgb; else pf = bmp.PixelFormat; Bitmap tmp = new Bitmap(w, h, pf); Graphics g = Graphics.FromImage(tmp); g.Clear(bkColor); g.DrawImageUnscaled(bmp, 1, 1); g.Dispose(); ...

비트맵 리사이징 메써드

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication6 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         public static Bitmap ResizeBitmap(Bitmap bmp, float ratio, InterpolationMode im)         {             int w = bmp.Width;             int h = bmp.Height;             Bitmap tmp = new Bitmap((int)(w * ratio), (int)(h * ratio), bmp.PixelFormat);             Graphics g = Graphics.FromImage(tmp...

드로우 위치/ Point()/ PointF()/ 10F/ RectAngle/ DrawImageUnscaled

이미지

테두리 넣기/ PixelFormat/ FromImage/ Clear/ Color.Red

이미지

using System.Drawing, openFileDialog, DialogResult.OK, Image.fromFile()

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication5 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         private void Form1_Load(object sender, EventArgs e)         {             if (openFileDialog1.ShowDialog(this) == DialogResult.OK)             {                 Image img = Image.FromFile(openFileDialog1.FileName);                 Form1.ActiveForm.BackgroundImage = img;          ...

Long, Int64

using System; namespace Console1 { class Class1 { static void Main() { int intVal = 1000; long longVal = intVal; Console.WriteLine("intVal = {0} = longVal = {1}", intVal, longVal); longVal = Int64.MaxValue; intVal = (int) longVal; Console.WriteLine("intVal = {0} = longVal = {1}", intVal, longVal); } } // class }

정적변수

이미지

int, Int32, i.MaxValue, Console.WriteLIne(), i.ToString()

이미지

반복문 제어문 탈출, 재귀:Break, Continue

using System; class BreakTest{ public static void Main(){ for (int i = 0; i<10; i++){ for (int j = 0 ; j<10; j++) { if (j==i) break; // ******** Console.Write(j + "\t"); } Console.WriteLine(""); } }//main }//class

우편번호 형식 검증

우편번호 형식 검증 /// <summary> /// 우편번호가 올바른 형식인 지 확인함. /// </summary> /// <param name="Value">우편번호</param> /// <param name="ErrMsgIs">리턴값이 false일 때 설정되는 에러 메세지</param> /// <example> /// Console.WriteLine(IsValidZipCode("435050", out ErrMsgIs)); //true /// Console.WriteLine(IsValidZipCode("435-050", out ErrMsgIs)); //true /// Console.WriteLine(IsValidZipCode("43550", out ErrMsgIs)); //false /// Console.WriteLine(IsValidZipCode("43-5050", out ErrMsgIs)); //false /// </example> public static bool IsValidZipCode(string Value, out string ErrMsgIs) { ErrMsgIs = ""; //435-050의 -를 뺌. int PosDash = Value.IndexOf("-"); if (PosDash == 3) { Value = Value.Substring(0, 3) + Value.Substring(4, 3); } try { int Num = Value.ToInt32(); } catch (Exception e) { ErrMsgIs = "우편번호가 숫자형식이 아닙니다."; retu...

DateTime, Now, Convert.ToSingle(), Math.PI

DateTime DateTime dateTime = DateTime.Now; //int hour = dateTime.Hour % 12; // also converts 24hrs to 12hrs format int minute = dateTime.Minute; int sec = dateTime.Second; //float hourRadian = Convert.ToSingle(hour* 360/12 * Math.PI/180); float minRadian = minute * 360/60 * Convert.ToSingle(Math.PI)/180; float secRadian = sec * 360/60 * Convert.ToSingle(Math.PI)/180; float hour = dateTime.Hour%12 + (float)dateTime.Minute/60; float hourRadian = hour * 360/12 * Convert.ToSingle(Math.PI)/180;

Bitmap, Width, Height, GetPixel, SetPixel, ToByte

이미지
private void button1_Click(object sender, System.EventArgs e) { Bitmap bitmap = new Bitmap("C:\\640480.bmp"); int bwidth = bitmap.Width; int bheight = bitmap.Height; this.Width=bwidth; this.Height=bheight; int i, j; byte gray; for (i = 0; i<bwidth; i++) { for (j=0; j<bheight; j++) { Color pixelColor = bitmap.GetPixel(i, j); int r = pixelColor.R; // the Red component int g = pixelColor.G; // the Red component int b = pixelColor.B; // the Blue component gray=Convert.ToByte(r*0.3+g*0.6+b*0.1); Color newColor = Color.FromArgb(gray, gray, gray); bitmap.SetPixel(i, j, newColor); } } this.BackgroundImage = bitmap; }

Image, This, MessageCaption

이미지

Close, Font, DrawString, SolidBrush

Close, Font, DrawString, SolidBrush private void button1_Click(object sender, System.EventArgs e) { Graphics g = this.CreateGraphics(); Font FT1 = new Font("Courier", 16); SolidBrush BR1 = new SolidBrush(Color.Chocolate); g.DrawString("C# Builder! 입니다 ~.", FT1, BR1, 50, 100); } // EXIT 버튼 핸들링 ------------------------------------------- private void button2_Click(object sender, System.EventArgs e) { WinForm.ActiveForm.Close(); }

StopWatch 사용예

using System; using System.Diagnostics; using System.Threading; class Program { static void Main() { // Create new stopwatch Stopwatch stopwatch = new Stopwatch (); // Begin timing stopwatch.Start(); // Do something for (int i = 0; i < 1000; i++) { Thread.Sleep(1); } // Stop timing stopwatch.Stop(); // Write result Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); } }

WinForm_Paint, Graphics, Pen, DrawLine, DashStyle

이미지

Color, FromArgb, FromName, ActiveForm, BackColor

이미지

namespace

using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; // *********** namespace P_Angle.Units // ************* { public class P_Angle { public const double Phi = 3.14159265; } } namespace P_Angle { public class WinForm : System.Windows.Forms.Form { ...

Color, GetPixel();, SetPixel();, FromArgb();, getC.R

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         private void Form1_Load(object sender, EventArgs e)         {             MessageBox.Show("Good~!");         }         private void button1_Click(object sender, EventArgs e)         {             Bitmap bmp1 = new Bitmap(@"C:\Users\sgi320\Desktop\lena.bmp");             Graphics g = this.Cre...

PointF, Convert.ToString, method

public double Angle(PointF Pt1, PointF Pt2) //********** { double result; // 각도 계산 result = Math.Atan((Pt2.Y - Pt1.Y) / (Pt2.X - Pt1.X)); return result; } //************** private void button1_Click(object sender, System.EventArgs e) { PointF P1 = new PointF(-2.3f,3.1f); PointF P2 = new PointF(0.3f,-1.7f); double aa, bb; aa = Angle(P1, P2); bb = aa / Units.P_Angle.Phi * 180.0f; MessageBox.Show(Convert.ToString(Convert.ToString(bb))); }

폼에 이미지 깔기

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         private void Form1_Load(object sender, EventArgs e)         {             MessageBox.Show("Good~!");         }         private void button1_Click(object sender, EventArgs e)         {             Bitmap bmp1 = new Bitmap(@"C:\Users\sgi320\Desktop\lena.bmp");             Graphics g = this.Cre...

이벤트 대리자

이미지

오버플로우 예외처리

이미지

힙과 스택, 스태틱

이미지

형 알아내기, Boxing

이미지

형변환 점검예외처리 기능

이미지

Implicit 형변환

이미지

부정형(지그재그) 배열

이미지
string [][] strs=new string [5][]; string strs[0]=new string[3]; string strs[1]=new string[6]; string strs[2]=new string[4]; string strs[3]=new string[6]; string strs[4]=new string[2];

2차원 배열

using System; namespace ArrayEx2 { class Class1 { static void Main(string[] args) { string[,] strJobs=new string[,] { // 2차원 배열 {"마법사","마법을 부리는 사람"}, {"검사","검을 잘 쓰는 사람"}, {"도둑넘","나쁜 사람"}, {"강아지","착한 동물"}, {"쓰레기","꼬락스"} }; // string Console.WriteLine("직업:"+strJobs[2,0]+" ,설명:"+strJobs[2,1]); } } // class }

상수와 스태틱

상수와 읽기전용 변수 private void WinForm_Load(object sender, System.EventArgs e) { const int i=100; MessageBox.Show("상수 "+i); } ② 읽기전용 변수의 경우에는 프로그램이 작동하면서 값이 할당되지만, 상수의 경우에는, 컴파일시 할당된다. ③ 상수는 특별히 지정하지 않아도 언제나 static이다.

변수의 Scope

using System; public class Scope { public int i=0; // Field 변수(전역) public static void Main() { { string str="나는 공산당이 싫어요!"; }//str은 여기에서 생명이 끝난다. { string str="나는 콩사탕이 싫어요!"; //str변수 중복 가능 } int i=100; // 지역변수(중복 가능) Console.WriteLine(i); } }

구조체와 열거형

구조체, 열거형 C#에서의 열거형은 그 자체가 하나의 형식이고 열거형 아래에 정의된 상수들은 멤버 상수가 된다. 하지만 C++에서의 열거형은 열거형 형식 그 자체의 의미보다는 상수들이 전역적으로 쓰일 수 있다는 것에 더 초점을 둔다. using System; namespace StructEx { public struct NameCard //네임카드 구조체, 디폴트는 private { public string strName; //이름 public int nAge; //나이 public string strCelNum; //핸드폰 번호 } class myClass { static void Main(string[] args) { NameCard n1=new NameCard(); n1.strName="둘리"; n1.nAge=10; n1.strCelNum="010-9591-XXXX"; NameCard n2=n1; n2.strName="고길동"; n2.nAge=45; Console.WriteLine("이름:"+n1.strName+" 핸폰버노:"+n1.strCelNum+" 나이:"+n1.nAge); Console.WriteLine("이름:"+n2.strName+" 핸폰버노:...

자료형

이미지

산술연산 검사 옵션

산술연산 검사 산술 연산은 컴파일러의 옵션 지정에 따라서 /checked+ 로 지정된 경우 모든 코드 범위에서 엄격한 산술 연산 검사를 할 수 있으며 /checked- 로 지정된 경우 모든 코드 범위에서 산술 연산 검사를 하지 않도록 할 수 있다

CSC compiler for terminal

이미지
IDE 의 기동은 첫회만 1분약 기다리게 되지만, 2회째 이후는 몇 초로 일어선다.Pentium1G RAM384MB 에서도 스트레스 없게 동작하는 것 같다. 이것으로 완성된다 *.cs 는, Program.cs Form1.cs Form1.Desiner.cs 의 3개로 구성된다. //---------------------------------------------------------------------- using System; // NameSpace 참조 for Console.Write.. namespace HelloTest // 새 NameSpace 구현 { class HelloWorld { // 새 Class 구현 public static int Main() { // 접근제한자_정적여부_리턴형_함수명(매개변수) Console.WriteLine("Hello Park!"); return 0; // 정수로 리턴(int) }//main }//class }// namespace 파일명 Hello.csc로 저장