블로그 이미지
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-25 09:56

Library File :




DEVIL.NET has been included in the main DEVIL distribution

Go to the DevIL image library website for the entire package. Here after you can find the older releases and, when a new one will get released, the newer ones.

WHAT IS DEVIL.NET ?

I’ve written a small wrap around the DevIL image library .

As for the .NET viewer, this is a “2 hour project” – that is a project I’ve written in 2 hours before going to sleep.. so no warranty is included! ;)

NOTE : This project is intentionally minimalist. If you want a more complete wrapper over DevIL, have a look at the Tao.Framework.

It allows any .NET program (VB.NET, C#, etc) to open and save files in all formats supported by the DevIL library. Also it opens them as System.Drawing.Bitmap objects, so that it works optimally with existing code.

As now it supports loading in bmp cut dcx dds ico gif jpg lbm lif mdl pcd pcx pic png pnmpsd psp raw sgi tga tif wal act pal and Doom graphics

And saving in : bmp dds jpg pcx png pnm raw sgi tga tif pal

Using it is simple.

As an example you can load/save a picture in a picturebox using (C# and VB.NET):


// C#
System.Drawing.Bitmap bmp = DevIL.DevIL.LoadBitmap(filename);
pictureBox1.Image = bmp;

‘ VB.NET
Dim bmp as System.Drawing.Bitmap
bmp = DevIL.DevIL.LoadBitmap(filename)
pictureBox1.Image = bmp

And you can save the picturebox image using :


// C#
System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)pictureBox1.Image;
DevIL.DevIL.SaveBitmap(filename, bmp);

‘ VB.NET
Dim bmp as System.Drawing.Bitmap
bmp = pictureBox1.Image
DevIL.DevIL.SaveBitmap(filename)
LICENSE & VERSION
C++.NET (Managed C++) Source is included and released under a choice of BSD or LGPL license. You can contact me for additional licensing options if you need them. Binaries are provided in the package, compatible with every version of .NET Framework (from 1.0 to 3.0).
SAMPLES
You can download samples for DevIL.NET library. The sample program is a small utility which acts as a viewer and a converter of image files, written in both C# and VB.NET.

RELEASE NOTES
I’ve done many tries and it seems the stride in .NET framework for 32bit images is always 4*width. While this can be expected, effectively the stride could have any value. As now the code relies heavily on a predictable stride to optimize memory copies.. please report me any bug (marcoPLEASEDELTHIS@mastropaolo.com), especially if you think a different stride is in place.

UPDATES

  • March 4th, 2007 : Release Version 1.3
  • July 12th, 2005 : Fixed a minor bug in initialization, uploaded samples
  • August 23th, 2005 : Release Version 1.1
  • December 8th, 2004 : Release Version 1.0

VERSION 1.1 CHANGES

  • Fixed a bad bug when loading non true color images (above all GIFs)
  • Implemented a new LoadBitmapAndScale which allows for the bitmap to be scaled directly in DevIL.NET
  • Started to implement some error handling…
  • note: From version 1.1, DevIL.NET may require ILU.dll to be installed in addition to DevIL.DLL. Since having an additional DLL is always a burden, ILU.dll is loaded dinamically and it’s not required unless the scale/resize feature is used ;)

VERSION 1.2 CHANGES

  • Support for VS2005, .NET Framework 2.0 on x86 platforms
  • NOTE : When using Devil.NET 1.2 on VS2005, remind to set your projects to use the x86 CPU. Otherwise the program may fail to run on x64 platforms.

VERSION 1.3 CHANGES

  • Fixed the infamous vertical flip bug
  • The v-flip can be done both in ILU code or .NET framework (depending on whether ILU.DLL has been loaded or not; you can load ILU.DLL either by loading an image with scale options or through the LoadILU method).
  • A DevIL.NET2.DLL exists. This is a framework 2.0/3.0 only version which is just a bit smaller than the “every” framework version.

Download Library Version 1.3
Download Library Version 1.2
Download Library Version 1.1
Download Library Version 1.0
Download VC++ sources and project
Download C# and VB.NET Samples
View the source online

반응형
Posted by blueasa
, |

최근 만들고 있는 프로그램에 사용할 음성재생 라이브러리를 이것저것 살펴보다가..

WMPLib, MBroMP3, DirectX.AudioVideoPlayback 이렇게 3가지를 놓고 상당한 고민을 했습니다.

이것저것 살펴본결과, 직접 구현하면서 사용하기에는 DirectX.AudioVideoPlayback이 수월해보여 이녀석으로 결정했습니다.

기념으로 DirectX.AudioVideoPlayback을 사용해서 간단하게 음성파일 재생을 구현해 보도록하겠습니다.

 

Microsoft.DirectX.AudioVideoPlayback을 사용하면 생각보다 간편하게 기능을 구현할 수 있습니다만..

.NET 1.1에서 구현된 녀석들을 .NET 2.0에서 사용하면 등장하는 문제인 LoaderLock 버그가 여기에도 존재합니다.

차근차근 구현하고.. 이 LoaderLock이 등장하지 않도록 하는 것까지 오늘은 알아보도록 하겠습니다.

 

우선 가장 먼저 해야할 일은 이 녀석을 사용하기 위한 준비과정이 되겠죠?

아래 그림처럼 참조추가의 .NET탭에서 Microsoft.DirectX.AudioVideoPlayback 항목을 선택해줍니다.


 

 

그러면 솔루션 탐색기에서 추가된 참조를 확인할 수 있습니다.

이녀석을 더블클릭해서 개체 브라우저로 잠시 우리가 사용할 녀석을 확인해보도록하지요.

 


이처럼 설명도 모두 나와있으니, 참고하시면 되겠습니다.

기본적으로 필요한 메소드와 프로퍼티는 모두 제공하고 있으므로 생각보다 쉬울 것 같습니다.

 

간단하게 폼이 로드되면 재생되는 코드를 만들어 볼까요?


그림과 같이 사용하시면 해당 경로의 음악파일을 자동으로 재생합니다. 두 번째 인자를 false로 주면 자동 재생은 안되죠.

이 외에 필요시에는 Play()나 Open()메소드를 이용하시면 되겠습니다.

 

이렇게 했지만.. 아마도 막상 시작을하면 LoaderLock예외가 발생하면서 프로그램이 중단될 것입니다.

아래와 같이 하면.. 완전히 해결하는 것은 아니지만, 프로그램이 죽지않게 할 수 있습니다.

(제가 알고 있는 완벽하게 해결하는 방법은 .Net Framework 1.1을 설치하는 것입니다.)

 

디버그 -> 예외 -> Managed Debugging Assistant -> LoaderLock의 Throw속성을 체크해제합니다.


 

 

LoaderLock예외를 이렇게 처리하고나면 이녀석을 컨트롤과 연결시켜서 사용자의 요구에 따라서 동작하는

재생프로그램을 만들고 싶으실지도 모르겠습니다.

재생시간이나 볼륨을 TrackBar와 연동시키고 싶다면.. TrackBar를 생성하고 TrackBar의 ValueChanged이벤트가

발생했을 때, 해당 Value를 받아와서 수행시키게하고... 재생, 중지등에 대한 적절한 이미지를 만들어 주고, 이 녀석들에 대한 Click이벤트를 Stop(), Pause()등의 메소드들과 연결하시면 되겠습니다.

 

 

문제는 재생중에 재생시간에 대한 TrackBar를 움직여야 한다는 점인데요. 이 부분은 쓰레드로 해결을 하는 수밖에 없겠지요.

Invoke를 사용해서 한다면 특별한 문제점은 없을거라고 생각합니다만..

처음에 언급했던 너무 완벽한 버그인 LoaderLock때문에 문제점이 발생하지 않을지는 저도 해보아야 알것 같습니다.

이 부분은 해보고 빠른 시일내에 이 글을 수정하는 식으로 업데이트하도록 하겠습니다.

 -> 확인결과 이상없이 잘 수행됩니다.

 

 

 

이로써 간단하게 음악파일을 재생할 수 있는 기능을 살펴보았습니다.


 
[출처] 〃C# DirectX.AudioVideoPlayback를 이용한 음성파일 재생.|작성자 Chuls

반응형
Posted by blueasa
, |

C#에서 DirectX를 활용하여 Wave파일을 재생하기 위해서는

새로운 참조를 추가해야 한다...

 

 

 

참조 추가 창에서 .NET 텝을 선택한 후 다음의 두 가지 구성요소를 선택한다.

 

      - Microsoft.DirectX

      - Microsoft.DirectX.DirectSound

 

 

 

참조 추가가 완료되면 솔루션 탐색기의 참조 리스트에 나타나게 된다.

 

 

 

그런 다음 소스 코드에 필요사항을 기입한다.

 

// 해당 참조 포함하기

using Microsoft.DirectX;

using Microsoft.DirectX.DirectSound;

 

// Device 생성자와 Buffer 선언 : Form1 클래스

private Device dsDevice = null;
private SecondaryBuffer buffer = null;

 

// Device 선언 및 설정 : InitializeComponent() 하위
dsDevice = new Device();
dsDevice.SetCooperativeLevel(this, CooperativeLevel.Normal);

 

// 실제 재생 부분

buffer = new SecondaryBuffer("sample.wav", dsDevice);
if(dsDevice != null) buffer.Play(0, BufferPlayFlags.Default);

 

 

DirectX를 활용하여 Wave파일을 재생하면

Winmm.dll API를 사용할 때와 달리 중복하여

Wave파일을 재생할 수 있다.


출처 : http://blog.naver.com/hero_juni/90034144815
반응형
Posted by blueasa
, |
public class dgv : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData)
{
Keys key = (keyData & Keys.KeyCode);
if (key == Keys.Enter)
{
return this.ProcessRightKey(keyData);
}
return base.ProcessDialogKey(keyData);
}
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
return this.ProcessRightKey(e.KeyData);
}
return base.ProcessDataGridViewKey(e);
}
}



반응형
Posted by blueasa
, |

namespace PropertyGridP

{

    public partial class Form5 : Form

    {

        public Form5()

        {

            InitializeComponent();

        }

 

        private void Form5_Load(object sender, EventArgs e)

        {

            foreach (Control c in this.propertyGrid1.Controls)

            {

                c.MouseClick += new MouseEventHandler(c_MouseClick);

            }

        }

 

        void c_MouseClick(object sender, MouseEventArgs e)

        {

            Control c = (Control)sender;

            MessageBox.Show(c.GetType().FullName);

        }

    }

}


출처 : 
http://social.msdn.microsoft.com/Forums/pl-PL/winforms/thread/ec88bdab-77a0-4dc1-9885-b2407c965166 

반응형
Posted by blueasa
, |

Introduction

This property grid control has been developed in Visual Studio C# 2008. This user control is similar to the standard Microsoft .NET 2.0 PropertyGrid control with several additional features:

  • Gets/sets any property item at runtime (e.g. change property’s help text)
  • New property items (Date and TimeDateTimeFileDirectoryProgressBar, ...)
  • Multi-language support
  • Image Preview
  • Date calendar
  • Numeric interval automatic validation
  • Customizable Boolean type (yes/no, true/false, ..)
  • Customizable engineering unit for numeric values
  • Use .NET standard dialog box, text title, new buttons (show text, apply), ...

This control is fully customizable at runtime. Property items can be added and changed at any time.

Background

The main problem of the Microsoft .NET 2.0 standard Property Grid Control is that it is not easy to control at run-time. Using this control is possible, for example, to change the language at runtime or to change a property that normally is read-only using the standard control.

Using the Code

To run the example project:

  1. Extract all files from ZIP into a folder
  2. Run Visual Studio C #2008 and select the command "File" > "Open project"
  3. Select the file "\Test\Test_mbrPropertyGrid\Test_mbrPropertyGrid.sln"
  4. Select the command "Build" > "Rebuild solution"
  5. Press the [F5] keyboard button to run the program

To build your new test project:

  1. Run Visual Studio C #2008 and create a new project (standard Windows form application)
  2. Add a reference to the .NET DLL "mbrPropertyGrid.dll"
  3. Right-click in toolbox windows and select the command "Choose Items..."
  4. Select the browse button and select the .NET DLL "mbrPropertyGrid.dll"
  5. Drag and drop the new PropertyGrid icon from the toolbox to your project form to add the control to your project
  6. Set the control properties to customize it
  7. Write code to add/manage property items

To logically group the various item objects, at first, add a category item:

mbrPropertyGrid.PropertyItemCategory catItem;
catItem = new mbrPropertyGrid.PropertyItemCategory("Main Category");
PropertyGrid1.CategoryAdd("CatMain", catItem);

To add property items to a category use the .ItemAdd method like the following example :

mbrPropertyGrid.PropertyItemInt32 intItem;
intItem = new mbrPropertyGrid.PropertyItemInt32("Line02 - Age (Int32)", 0);
intItem.SetValidationRange(0, 120, 1);
intItem.SetHelpCaptionText("Age", "Tell me your age (valid range : 0..120)");
PropertyGrid1.ItemAdd("CatMain", "MyAge", intItem);

mbrPropertyGrid.PropertyItemString strItem;
strItem = new mbrPropertyGrid.PropertyItemString
	("Line01 - Name (String)", "Jak", "Jak Smith");
strItem.HelpCaption = "Name";
strItem.HelpText = "Tell me your name...";
PropertyGrid1.ItemAdd("CatMain", "YourName", strItem);

To disable a property item, set the item property .Enabled to false like in the following example:

strItem = new mbrPropertyGrid.PropertyItemString
	("Line03 - Job (String)", "A software developer");
strItem.HelpText = "Tell me about your job";
strItem.Enabled = false;
PropertyGrid1.ItemAdd("CatMain", "K03", strItem);

When you have completed the addition of item objects to force the complete control repaint, run the.RefreshControl(true) method like in the following code:

// Full control repaint
PropertyGrid1.RefreshControl(true);

A quick screen shot control preview. Please note that the standard dialog box will be shown in the same language of the operating system.

mbrPropertygrid_Preview_02.png

mbrPropertygrid_Preview_03.png

mbrPropertygrid_Preview_04.png

mbrPropertygrid_Preview_05.png

mbrPropertygrid_Preview_06.png

mbrPropertygrid_Preview_07.png

mbrPropertygrid_Preview_08.png

mbrPropertygrid_Preview_09.png

mbrPropertygrid_Preview_10.png

mbrPropertygrid_Preview_11.png

mbrPropertygrid_Preview_12.png

mbrPropertygrid_Preview_12.png

mbrPropertygrid_Preview_13.png

Points of Interest

To change the language at runtime, simply change the following properties of the property items: Text,HelpCaptionHelpText (and Description for a Directory Item).

History

  • Version 1.0.0.0 - 28/08/2008: This is the first version. Some points have to be accommodated. For example, there is a known bug on a video refresh of the .Text property. I suggest, at the moment, to disable the Textproperty view by setting .TextVisible = false;

About Me

My name is Massimiliano Brugnerotto and I'm an Italian C# software developer. I believe that open source software is a useful resource and with this article, I will give my contribution to this site that on many occasions gave me interesting development solutions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


출처 :  http://www.codeproject.com/Articles/28933/A-C-2008-Advanced-Customizable-PropertyGrid-Contro
반응형

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

datagridview에 엔터키치면 오른쪽 셀 이동  (1) 2012.02.22
PropertyGrid catching mouse events  (1) 2012.02.01
Add NumericUpDown in PropertyGrid  (0) 2012.01.20
Nullable 형식 사용  (0) 2012.01.19
MeasureString(문자열 길이 체크)  (0) 2012.01.17
Posted by blueasa
, |
   public class NumericUpDownTypeEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            if (context == null || context.Instance == null)
                return base.GetEditStyle(context);
            
            return UITypeEditorEditStyle.DropDown;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            IWindowsFormsEditorService editorService;

            if (context == null || context.Instance == null || provider == null)
                return value;

            try
            {
                // get the editor service, just like in windows forms
                editorService = (IWindowsFormsEditorService)
                   provider.GetService(typeof(IWindowsFormsEditorService));

                NumericUpDown nmr = new NumericUpDown();
                nmr.Size = new Size(60, 120);
                nmr.Minimum = 0;
                nmr.Maximum = 200;
                nmr.Increment = 0.01M;         /// 업다운 증가 단위(float이 필요해서 0.01로 했음)
                nmr.DecimalPlaces = 6;        /// 소수 이하 표시할 자리 수.
                nmr.Value = new decimal((float)value);
                editorService.DropDownControl(nmr);

                return (float)nmr.Value;
            }
            finally
            {
                editorService = null;
            }
        }
    }
------------------------------------------------------------------------------------------------------

참조1 :  http://social.msdn.microsoft.com/Forums/da-DK/netfxbcl/thread/370ce9d3-fc44-4cdc-9c76-dd913c9b572f 

참조2 : http://social.msdn.microsoft.com/forums/en-US/winforms/thread/5441df96-5b72-4b99-8033-d467bd700c78
반응형

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

PropertyGrid catching mouse events  (1) 2012.02.01
A C# 2008 Advanced Customizable PropertyGrid Control  (0) 2012.01.26
Nullable 형식 사용  (0) 2012.01.19
MeasureString(문자열 길이 체크)  (0) 2012.01.17
Convert String To Enum Instance  (0) 2011.12.16
Posted by blueasa
, |

Nullable 형식 사용

Programming/C# / 2012. 1. 19. 11:33
Visual Studio 2005
1명 중 1명이 도움이 되는 것으로 평가 이 항목 평가

nullable 형식을 사용하면 내부 형식의 값을 모두 나타낼 수 있을 뿐만 아니라 null 값을 추가로 나타낼 수 있습니다. nullable 형식은 다음과 같은 두 가지 방법 중 하나로 선언됩니다.

System.Nullable<T> variable

- 또는 -

T? variable

T는 nullable 형식의 내부 형식입니다. T는 struct를 비롯한 임의의 값 형식이 될 수 있지만 참조 형식은 될 수 없습니다.

nullable 형식이 필요한 경우를 예로 들면, true와 false라는 두 가지 값만 갖는 일반적인 부울 변수를 생각해 볼 수 있습니다. 이런 변수에는 "정의되지 않은 상태"를 의미하는 값이 없습니다. 여러 프로그래밍 응용 프로그램에서 변수는 정의되지 않은 상태로 있을 수 있으며, 데이터베이스 상호 작용이 가장 대표적인 예입니다. 예를 들어, 데이터베이스의 필드는 true나 false 값을 포함할 수 있지만 값을 전혀 포함하지 않을 수 있습니다. 마찬가지로, 참조 형식이 초기화되지 않았음을 나타내기 위해 이를 null로 설정할 수 있습니다.

이러한 차이를 처리하기 위해서는 상태 정보를 저장하기 위한 추가 변수 사용, 특수 값 사용 등 별도의 프로그래밍 작업이 필요할 수 있습니다. C#에서 nullable 형식 한정자를 사용하면 정의되지 않은 값을 나타내는 값 형식 변수를 만들 수 있습니다.

nullable 형식의 기준으로는 모든 값 형식을 사용할 수 있습니다. 예를 들면 다음과 같습니다.

int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];

nullable 형식의 각 인스턴스에는 읽기 전용인 공용 속성이 두 개 있습니다.

  • HasValue

    HasValue는 bool 형식이며, 변수에 null이 아닌 값이 포함되어 있으면 true로 설정됩니다.

  • Value

    Value는 내부 형식과 동일한 형식입니다. HasValue가 true이면 Value에는 의미 있는 값이 포함됩니다. HasValue가 false인 경우에 Value에 액세스하려고 하면InvalidOperationException이 throw됩니다.

이 예제에서는 HasValue 멤버를 사용하여 변수의 값을 표시하려고 하기 전에 변수에 값이 포함되어 있는지 테스트합니다.

int? x = 10;
if (x.HasValue)
{
    System.Console.WriteLine(x.Value);
}
else
{
    System.Console.WriteLine("Undefined");
}

값은 다음과 같은 방법으로도 테스트할 수 있습니다.

int? y = 10;
if (y != null)
{
    System.Console.WriteLine(y.Value);
}
else
{
    System.Console.WriteLine("Undefined");
}

nullable 형식은 Value 속성을 사용하거나 명시적으로 캐스팅하여 일반 형식으로 캐스팅할 수 있습니다. 예를 들면 다음과 같습니다.

int? n = null;

//int m1 = n;      // Will not compile.
int m2 = (int)n;   // Compiles, but will create an exception if x is null.
int m3 = n.Value;  // Compiles, but will create an exception if x is null.

두 데이터 형식 사이에 사용자 정의 변환이 정의되어 있는 경우에는 이러한 데이터 형식의 null 허용 버전에 대해서도 동일한 변환을 사용할 수 있습니다.

nullable 형식의 변수는 다음과 같이 null 키워드를 사용하여 null로 설정할 수 있습니다.

int? n1 = null;

일반 형식에서 nullable 형식으로의 변환은 암시적입니다.

int? n2;
n2 = 10;  // Implicit conversion.

값 형식에 사용되는 미리 정의된 단항 및 이항 연산자와 모든 사용자 정의 연산자는 nullable 형식에도 사용할 수 있습니다. 피연산자가 null이면 이러한 연산자는 null 값을 생성합니다. 그렇지 않으면 연산자는 포함된 값을 사용하여 결과를 계산합니다. 예를 들면 다음과 같습니다.

int? a = 10;
int? b = null;

a++;         // Increment by 1, now a is 11.
a = a * 10;  // Multiply by 10, now a is 110.
a = a + b;   // Add b, now a is null.

nullable 형식과 비교를 수행하는 경우 nullable 형식 중 하나가 null이면 비교 결과는 항상 false입니다. 따라서 비교 결과가 false라고 해서 그 반대 경우가 true라고 단정할 수는 없습니다. 예를 들면 다음과 같습니다.

int? num1 = 10;
int? num2 = null;
if (num1 >= num2)
{
    System.Console.WriteLine("num1 is greater than or equal to num1");
}
else
{
    // num1 is NOT less than num2
}

위의 else 문에서 내린 결론은 유효하지 않습니다. num2가 null이므로 값을 포함하지 않기 때문입니다.

모두 null인 두 nullable 형식을 비교할 경우 결과는 true입니다.

?? 연산자는 null이 허용되지 않는 형식에 nullable 형식을 대입할 때 반환되는 기본값을 정의합니다.

int? c = null;

// d = c, unless c is null, in which case d = -1.
int d = c ?? -1;

이 연산자는 여러 개의 nullable 형식과 함께 사용할 수도 있습니다. 예를 들면 다음과 같습니다.

int? e = null;
int? f = null;

// g = e or f, unless e and f are both null, in which case g = -1.
int g = e ?? f ?? -1;

bool? nullable 형식에는 truefalse 및 null의 세 가지 값이 포함될 수 있습니다. 따라서 iffor 또는 while 같은 조건문에서는 이를 사용할 수 없습니다. 예를 들어, 다음 코드는 컴파일되지 않고 컴파일러 오류 CS0266이 발생합니다.

bool? b = null;
if (b) // Error CS0266.
{
}

이 코드는 null이 조건문의 컨텍스트에서 무엇을 의미하는지 명확하지 않기 때문에 컴파일되지 않습니다. 조건문에 사용하기 위해 nullable 부울을 bool로 명시적으로 캐스팅할 수 있지만 개체의 값이 있고 이 값이 null이면 InvalidOperationException이 throw됩니다. 따라서 bool로 캐스팅하기 전에 HasValue 속성을 확인하는 것이 중요합니다.

nullable 부울은 SQL에 사용되는 부울 변수 형식과 비슷합니다. & 및 | 연산자로 생성되는 결과가 값이 세 개인 SQL 부울 형식과 일관성을 유지할 수 있도록 다음과 같은 미리 정의된 연산자가 제공됩니다.

bool? operator &(bool? x, bool? y)

bool? operator |(bool? x, bool? y)

다음 표에서는 이러한 연산자의 결과를 보여 줍니다.

Xyx&yx|y

True

true

True

true

True

false

False

true

True

null

Null

true

False

true

False

true

False

false

False

false

False

null

False

null

Null

true

Null

true

Null

false

False

null

Null

null

Null

null

반응형
Posted by blueasa
, |
반응형

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

Add NumericUpDown in PropertyGrid  (0) 2012.01.20
Nullable 형식 사용  (0) 2012.01.19
Convert String To Enum Instance  (0) 2011.12.16
문자열이 숫자 값을 나타내는지 확인  (0) 2011.12.16
Operator Overloading in C#  (2) 2011.12.05
Posted by blueasa
, |

Summary

Enums are a powerful construction in C# and other programming languages when you are working with finite sets such as fruits, days of the week or colors. Visual Studio's Intellisense is very nice with Enums because it lists all the options for the programmer to choose from. But quite often you want to print enums, compare int values, or serialize an enum--and then you have to do some conversions.The following method may be run in the code-behind file of an ASPX page where you have added a Label control named lblOutput. However, this technique will work in any C# program, not just ASP.NET.

Example: Convert string to Enum instance

public void EnumInstanceFromString()
{
   // The .NET Framework contains an Enum called DayOfWeek.
   // Let's generate some Enum instances from strings.

   DayOfWeek wednesday = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Wednesday");
   DayOfWeek sunday = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "sunday", true);
   DayOfWeek tgif = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "FRIDAY", true);

   lblOutput.Text = wednesday.ToString() 
      + ".  Int value = " + ((int)wednesday).ToString() + "<br>";
   lblOutput.Text += sunday.ToString() 
      + ".  Int value = " + ((int)sunday).ToString() + "<br>";
   lblOutput.Text += tgif.ToString() 
      + ".  Int value = " + ((int)tgif).ToString() + "<br>";

}
The Enum.Parse method takes two or three arguments. The first is the type of the enum you want to create as output. The second field is the string you want to parse. Without a third input, the case of the input string must match an enum instance or the conversion fails. But the third input indicates whether to ignore case. If true, than wEdNEsDAy will still get converted successfully.

Example: Output

Wednesday. Int value = 3
Sunday. Int value = 0
Friday. Int value = 5

출처 :  http://www.cambiaresearch.com/articles/47/convert-string-to-enum-instance
반응형

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

Nullable 형식 사용  (0) 2012.01.19
MeasureString(문자열 길이 체크)  (0) 2012.01.17
문자열이 숫자 값을 나타내는지 확인  (0) 2011.12.16
Operator Overloading in C#  (2) 2011.12.05
Force property update in propertygrid  (0) 2011.11.29
Posted by blueasa
, |