블로그 이미지
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 21:33

프로그래밍을 할 때 있어서 모든 일이 처음 설계한대로 흘러간다면 얼마나 좋을까? 하지만 Hello World를 출럭하는 프로그램이 아닌 이상에야 그런 일은 있을 수 없다.


확장성을 위해, 재사용성을 위해, 더 나은 구조를 위해 코드와 설계는 변하기 마련이다. 그 와중에 많은 함수나 변수, 클래스가 추가되고 삭제된다. 물론 혼자서만 하는 작업이라면 코드를 바꾸고 바꾼 코드를 바로 적용하면 되지만, 코드 베이스를 만드는 사람과 그 베이스를 이용해서 작업하는 사람이 따로 있는 상황이라면 이야기가 조금 달라진다. 


만약 베이스를 작업하는 사람이 몇몇의 함수를 삭제하고 다른 이름의 함수로 대체했다면 그 베이스를 응용하는 사람 역시 그에 대한 사실을 알아야 한다. 물론 일반적인 상식으로 베이스 작업자가 베이스를 변경했다면 다른 작업자에게 바로 알려주고 다른 작업자는 바로 변경하는게 맞는 이야기지만, 사람과 사람 사이의 의사소통이라는게 말처럼 쉽기만 하던가. 베이스 작업자가 변경사항을 몇 개는 빠뜨리고 알려줄 수도 있고, 다른 작업자는 이야기를 들었지만 까먹을 수도 있는 일이다. 여튼 의사소통 과정에서 문제가 발생했다면 다른 작업자는 뜬금없이 바뀐 베이스 코드에 당황을 금치 못할 것이다.


그런 상황을 맞이한 다른 작업자는 당연히 문제를 해결하기 위해서 베이스 작업자에게 어떻게 변경된 것인지 물어보던지, 코드를 뒤져서 바뀐 함수를 적용하던지 하는 노력을 하겠지만 아무래도 이런 방식은 해결 속도도 느릴 뿐더러 효율적이지 못하다.


그렇기 때문에 나온 해결책이 바로 [Obsolete] 라는 어트리뷰트이다. 


class TestClass
{
    [Obsolete]
    public void Function1()
    {
    }
}


더 이상 사용하지 않거나 그럴 예정인 클래스나 함수, 변수의 앞에 [Obsolete] 어트리뷰트를 붙여주면 된다. 그렇게 하면 해당 함수를 호출할 때 초록색 밑줄과 함께 더 이상 사용하지 않는 함수라는 경고가 뜬다.



그리고 툴팁에서는 함수 앞에 [deprecated]가 붙게 된다.


이 [Obsolete]는 세 가지 방식의 오버로딩을 지원한다.


class TestClass
{

    [Obsolete]
    public void Function1()
    {

    }

    [Obsolete("Not use anymore.")]
    public void Function2()
    {

    }

    [Obsolete("Not use anymore.", true)]
    public void Function3()
    {

    }
}


[Obsolete] :: 더 이상 사용하지 않는 코드라는 경고만 출력한다.


[Obsolete(string message)] :: 더 이상 사용하지 않는다는 경고에 추가적인 메시지를 남길 수 있다. 이 메시지를 통해 더 이상 사용하지 않는 코드 대신에 사용할 코드를 사용자에게 알릴 수 있다.


[Obsolete(string message, bool error)] :: 추가적인 로그와 함께 이 코드를 사용할 경우에 컴파일 에러를 띄울지를 결정한다. true를 넣어주면 컴파일 에러를 띄워서 이 코드를 사용하면 컴파일을 할 수 없게 된다.



이런 식으로 [Obsolete]를 적절하게 사용하면 베이스 작업자는 코드 작업만으로 다른 작업자에게 코드가 변경되었음을 알림과 동시에 그에 대한 해결책도 전해줄 수 있다. 베이스 작업자가 코드를 변경하고 다른 작업자에게 변경사항을 일일이 알리는 것보다 훨씬 빠르고 효율적인 해결책이다.



출처: http://wergia.tistory.com/23 [베르의 프로그래밍 노트]



참조 : http://answers.unity3d.com/questions/559529/how-to-mark-a-method-obsolete.html

반응형

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

ODBC/OleDB로 Excel 읽어서 처리할 때, 255자로 짤리는 경우  (0) 2018.04.13
Dictionary for Loop in C#  (0) 2017.12.05
[펌] string을 byte[] 배열로 변환?  (0) 2017.01.10
[펌] 반복문 유틸  (0) 2016.12.07
[펌] Loop Dictionary  (0) 2016.12.07
Posted by blueasa
, |
string을 byte[] 배열로 변환? 

string 문자열을 C#의 Char[] 배열로 변경하는 것은 String 클래스의 ToCharArray()라는 메서드를 사용하면 간단하다. 그렇다면, string은 byte[] 배열로 변경하는 것은 가능한가? 만약 가능했다면, string 클래스 안에 ToByteArray() 같은 메서드가 존재할 듯 한데, 이런 메서드는 존재하지 않는다. 왜냐하면, String은 직접 byte[] 변경할 수 없기 때문이다. 먼저 반대의 경우를 생각해 보자. byte[]를 직접 string으로 변경할 수 있는가? 이를 위해 우선 byte[] 가 어떤 Charset을 가지고 인코딩(Encoding) 되었는지 알아야 할 것이다. 이는 아스키, 유니코드, UTF8, GB18030 등 다양한 인코딩 방식에 따라 바이트들이 의미하는 문자가 완전히 다르기 때문이다. 따라서 byte배열을 .NET의 유니코드 string으로 변경하기 위해서는 해당 바이트가 어떤 인코딩인지 알고 이를 유니코드 String으로 변경하게 된다. 동일한 로직으로 문자열을 Byte배열로 변경할 때도 인코딩 방식에 따라 다른 바이트값들을 갖게 된다. 



String을 Byte[]로 인코딩 

문자열을 Byte[] 배열로 변경하기 위해서는 System.Text.Encoding의 인코딩 방식을 지정한 후 GetBytes() 메소드를 호출하면 된다. 예를 들어, 유니코드 인코딩을 사용하여 Byte[]로 변환하는 경우, System.Text.Unicode.GetBytes() 메서드를 호출하고, UTF8 인코딩을 사용하는 경우, System.Text.UTF8.GetBytes() 메서드를 호출하면 된다. 

예제

// String을 Char[]로 변환 
string str = "Hello 한국";
char[] uchars = str.ToCharArray();

// String은 바이트로 직접 변환할 수 없으며,
// Encoding을 통해 변환 가능. 16바이트 생성
byte[] ubytes = System.Text.Encoding.Unicode.GetBytes(str);

// 보다 컴팩트한 UTF8 인코딩. 12바이트 생성
byte[] utf8bytes = System.Text.Encoding.UTF8.GetBytes(str);




Byte[]을 String으로 변환 

Byte[] 배열을 String으로 변환하기 위해서는 바이트로 인코딩했던 동일한 인코더를 사용하여야 한다. 즉, 유니코드 인코더를 사용하여 String은 Byte[]로 변환했었다면 Encoding.Unicode.GetString()을 사용하여 Byte 배열을 문자열로 변경한다. 

예제

using System.Text;

// Byte Array를 String으로 변환 
string s1 = Encoding.Unicode.GetString(uniBytes);
string s2 = Encoding.UTF8.GetString(utf8bytes);




char[]을 String으로 변환 

char[] 배열을 String으로 변환하는 것은 간단하다. C#에서 char는 이미 유니코드이고, string 문자열은 이런 유니코드 문자 요소들의 집합이므로 String 생성자에 문자배열을 직접할당하여 변환할 수 있다. 




BASE64 인코딩 

Byte[] 배열을 웹상에서 전송하기 위해 많이 사용되는 방식으로 BASE64 인코딩을 들 수 있다. 송신 쪽에서는 Convert.ToBase64String(byte[])를 사용하여 바이트들을 BASE64 인코딩된 문자열로 변경하고 String을 전송하게 되고, 수신 쪽에서는 Convert.FromBase64String(string)을 사용하여 BASE64 인코딩된 문자열을 다시 바이트 배열로 변경하여 사용하게 된다. 

예제

// Byte Array를 BASE64 Encoding
string s64 = Convert.ToBase64String(utf8bytes);

// BASE64 인코딩한 String을 다시 Byte Array로
byte[] bytes64 = Convert.FromBase64String(s64);



[출처] http://www.csharpstudy.com/Tip/Tip-string-encoding.aspx

반응형
Posted by blueasa
, |

[펌] 반복문 유틸

Programming/C# / 2016. 12. 7. 17:54
// 반복문 관련
    // For Array
    public static void ForToArray

(T[] pArray, Action pCallback) { if (null == pArray) return; if (null == pCallback) return; int iMaxCount = pArray.Length; for (int iLoop=0; iLoop < iMaxCount; ++iLoop) { pCallback(pArray[iLoop]); } } // For Enum public static void ForToEnum(Action pCallback) { var pEnumerator = Enum.GetValues(typeof(T)).GetEnumerator(); while (pEnumerator.MoveNext()) { pCallback((T)pEnumerator.Current); } } // For List public static void ForToList(List pList, Action pCallback) { if (null == pList) return; if (null == pCallback) return; int iMaxCount = pList.Count; for (int iLoop = 0; iLoop < iMaxCount; ++iLoop) { pCallback(pList[iLoop]); } } public static void ForToList(List pList, Func pCallback) { if (null == pList) return; if (null == pCallback) return; int iMaxCount = pList.Count; for (int iLoop = 0; iLoop < iMaxCount; ++iLoop) { if (true == pCallback(pList[iLoop])) break; } } // For Dictionary public static void ForToDic(Dictionary pDic, Action pCallback) { if (null == pDic) return; if (null == pCallback) return; var pEnumerator = pDic.GetEnumerator(); while (pEnumerator.MoveNext()) { var kvp = pEnumerator.Current; pCallback(kvp.Key, kvp.Value); } } public static void ForToDic(Dictionary pDic, Func pCallback) { if (null == pDic) return; if (null == pCallback) return; var pEnumerator = pDic.GetEnumerator(); while (pEnumerator.MoveNext()) { var kvp = pEnumerator.Current; if (true == pCallback(kvp.Key, kvp.Value)) break; } } // For One public static void For(int iStartIndex, int iMaxIndex, Action pCallback) { for (int iLoop = iStartIndex; iLoop pCallback) { for (int iLoop = iStartIndex; iLoop < iMaxIndex; ++iLoop) { if (true == pCallback(iLoop)) break; } } // For Double public static void ForToDouble(int iMaxToFirst, int iMaxToSecond, Action pCallback) { for (int iLoop1 = 0; iLoop1 < iMaxToFirst; ++iLoop1) { for (int iLoop2 = 0; iLoop2 < iMaxToSecond; ++iLoop2) pCallback(iLoop1, iLoop2); } } public static void ForToDouble(int iMaxToFirst, int iMaxToSecond, Func pCallback) { for (int iLoop1 = 0; iLoop1 < iMaxToFirst; ++iLoop1) { for (int iLoop2 = 0; iLoop2 < iMaxToSecond; ++iLoop2) { if (true == pCallback(iLoop1, iLoop2)) return; } } } // Inverse For Double public static void ForInverseToDouble(int iMaxToFirst, int iMaxToSecond, Action pCallback) { for (int iLoop1 = iMaxToFirst; iLoop1 >= 0; --iLoop1) { for (int iLoop2 = iMaxToSecond; iLoop2 >= 0; --iLoop2) pCallback(iLoop1, iLoop2); } } public static void ForInverseToDouble(int iMaxToFirst, int iMaxToSecond, Func pCallback) { for (int iLoop1 = iMaxToFirst; iLoop1 >= 0; --iLoop1) { for (int iLoop2 = iMaxToSecond; iLoop2 >= 0; --iLoop2) { if (true == pCallback(iLoop1, iLoop2)) return; } } }


[출처] 이상호

반응형
Posted by blueasa
, |

[펌] Loop Dictionary

Programming/C# / 2016. 12. 7. 17:43
Code (CSharp):
  1. var enumerator = my_dictionary.GetEnumerator();
  2. while( enumerator.MoveNext() )
  3. {
  4.     // Access value with enumerator.Current.Value;
  5. }



[출처] https://forum.unity3d.com/threads/c-dictionary-loop.337804/

반응형
Posted by blueasa
, |

I've come across the situation on a number of occasions when coding where I've wanted to convert from a string to an enum. In the Media Catalog sample, I resorted to one giant switch statement that has a case block for each string that returns an enum from it.

One of my colleagues came up with the answer yesterday; it's one of those methods that you can never find when you're looking for it, but once discovered it seems blindingly obvious:

   object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

So you can write the following kind of code:

   enum Colour
   {
      Red,
      Green,
      Blue
   } 

   // ...
   Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);
   Console.WriteLine("Colour Value: {0}", c.ToString());

   // Picking an invalid colour throws an ArgumentException. To
   // avoid this, call Enum.IsDefined() first, as follows:
   string nonColour = "Polkadot";

   if (Enum.IsDefined(typeof(Colour), nonColour))
      c = (Colour) Enum.Parse(typeof(Colour), nonColour, true);
   else
      MessageBox.Show("Uh oh!");

What a time saver - thanks, Simon!

Footnote: interestingly, whilst writing this up I noticed that Enum.IsDefined() doesn’t offer the ignoreCase parameter. If you don’t know whether the casing is right, it seems the only way to do the conversion is using the Parse method and catching the ArgumentException. That's not ideal, since it runs a lot slower. I wonder if this is a loophole in the design; no doubt someone like Brad could cast light on it...

posted on Friday, April 02, 2004 1:49 PM

Feedback

# re: How do you convert a string into an enum? 4/2/2004 7:22 PM SBC

You can get the string values of enums also by calling Enum.GetNames or Enum.GetName...




출처 : http://redccoma.tistory.com/117

반응형
Posted by blueasa
, |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Diagnostics;
  
Stopwatch SW = new Stopwatch();
string sTemp1, sTemp2;
 
SW.Reset();
SW.Start();
 
// " 측정할 부분 작성 "
SW.Stop();
 
// 현재 인스턴스가 측정한 총 경과 시간을 가져옵니다.
sTemp1 = SW.Elapsed.ToString();                             // EX) "00:00:00.0000045"
// 현재 인스턴스가 측정한 밀리초 단위의 총 경과 시간을 가져옵니다
sTemp2 = SW.ElapsedMilliseconds.ToString() ;          // EX) "44"


출처 : http://overit.tistory.com/entry/C-%EC%8B%9C%EA%B0%84%EC%B2%B4%ED%81%ACStopwatch

반응형
Posted by blueasa
, |

참조) http://blog.naver.com/goldrushing/130147289978

 

 

http://blog.naver.com/bridman/40195903160



 

참조에 위 Microsoft Excel 14.0 Object Library 를 추가하고 빌드를 하면 개발PC에서는 실행이 잘되지만

오피스가 설치되지 않은 다른 PC에서는 오류가 발생한다.

 

[오류] 'Microsoft.ACE.OLEDB.12.0' 공급자는 로컬 컴퓨터에 등록할 수 없습니다.

 

라는 오류 발생시 다음주소의 설치파일을 다운로드하여 설치해주면 된다.

 

http://www.microsoft.com/ko-kr/download/details.aspx?id=13255

 

나의 경우 64Bit PC여서 64Bit용으로 받아서 설치해주었다.

 

물론 Build시에도 AnyPC또는 64Bit용으로 빌드를 해주었다.




출처 : http://mydoh.tistory.com/63

반응형
Posted by blueasa
, |

Sorting Arrays

Programming/C# / 2014. 11. 21. 11:53

Sorting Arrays [C#]

This example shows how to sort arrays in C#. Array can be sorted using static method Array.Sortwhich internally use Quicksort algorithm.

Sorting array of primitive types

To sort array of primitive types such as intdouble or string use method Array.Sort(Array) with the array as a paramater. The primitive types implements interface IComparable, which is internally used by the Sort method (it calls IComparable.Com­pareTo method). See example how to sort int array:

[C#]

// sort int array
int[] intArray = new int[5] { 8, 10, 2, 6, 3 };
Array.Sort(intArray);
// write array
foreach (int i in intArray) Console.Write(i + " ");  // output: 2 3 6 8 10

or how to sort string array:

[C#]

// sort string array
string[] stringArray = new string[5] { "X", "B", "Z", "Y", "A" };
Array.Sort(stringArray);
// write array
foreach (string str in stringArray) Console.Write(str + " "); // output: A B X Y Z

Sorting array of custom type using delegate

To sort your own types or to sort by more sophisticated rules, you can use delegate to anonymous method. The generic delegate Comparison<T> is declared as public delegate int Comparison<T> (T x, T y). It points to a method that compares two objects of the same type. It should return less then 0 when X < Y, zero when X = Y and greater then 0 when X > Y. The method (to which the delegate points) can be also an anonymous method (written inline).

Following example demonstrates how to sort an array of custom type using the delegate to anonynous comparison method. The custom type in this case is a class User with properties Name and Age.

[C#]

// array of custom type
User[] users = new User[3] { new User("Betty", 23),  // name, age
                             new User("Susan", 20),
                             new User("Lisa", 25) };

[C#]

// sort array by name
Array.Sort(users, delegate(User user1, User user2) {
                    return user1.Name.CompareTo(user2.Name);
                  });
// write array (output: Betty23 Lisa25 Susan20)
foreach (User user in users) Console.Write(user.Name + user.Age + " ");

[C#]

// sort array by age
Array.Sort(users, delegate(User user1, User user2) {
                    return user1.Age.CompareTo(user2.Age); // (user1.Age - user2.Age)
                  });
// write array (output: Susan20 Betty23 Lisa25)
foreach (User user in users) Console.Write(user.Name + user.Age + " ");

Sorting array using IComparable

If you implement IComparable interface in your custom type, you can sort array easily like in the case of primitive types. The Sort method calls internally IComparable.Com­pareTo method.

[C#]

// custom type
public class User : IComparable
{
  // ...

  // implement IComparable interface
  public int CompareTo(object obj)
  {
    if (obj is User) {
      return this.Name.CompareTo((obj as User).Name);  // compare user names
    }
    throw new ArgumentException("Object is not a User");
  }
}

Use it as you sorted the primitive types in the previous examples.

[C#]

// sort using IComparable implemented by User class
Array.Sort(users);  // sort array of User objects



출처 : http://www.csharp-examples.net/sort-array/

반응형
Posted by blueasa
, |
List<cTag> week = new List<cTag>();
// add some stuff to the list
// now sort
week.Sort(delegate(cTag c1, cTag c2) { return c1.date.CompareTo(c2.age); });



참조 : http://stackoverflow.com/questions/3163922/sort-a-custom-class-listt

반응형
Posted by blueasa
, |

OleDB로 엑셀파일을 제어하는 툴을 만들었었는데,


MySheet$                                        // 내가 만든 Sheet

MySheet$_xlnm#_FilterDatabase        // 만들지도 않았고, 엑셀파일에서 보이지도 않음.


생각지도 못한 MySheet$_xlnm#_FilterDatabase 라는 Sheet Name이 뜨길래 뭔가 했는데 검색해보니 VB 관련으로 엑셀의 VBA를 쓰면 내부적으로 만들어서 사용하는 것 같다.


어쨌든 나에겐 필요없는 정보라서 Sheet Name에 "_FilterDatabase"가 포함되어 있으면 Skip하도록 소스를 조금 수정했다.



참조 : http://stackoverflow.com/questions/23034296/multi-sheet-import-with-oledb-netting-xlnm-filterdatabase-as-sheet-names

반응형

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

Sorting Arrays  (0) 2014.11.21
Sort a Custom Class List<T>  (0) 2014.09.29
Google Protocol Buffer 사용해보기 with C#  (0) 2014.09.16
Calendar Class[MSDN]  (0) 2014.09.01
C# 강의  (0) 2014.08.29
Posted by blueasa
, |