programing

가장 유용한 .NET 유틸리티 클래스 개발자는 재사용보다는 재발 명하는 경향이 있습니다.

nasanasas 2020. 12. 26. 15:29
반응형

가장 유용한 .NET 유틸리티 클래스 개발자는 재사용보다는 재발 명하는 경향이 있습니다.


나는 최근에 작년의 Phil Haack 포스트 ( The Most Useful .NET Utility Classes Developers Tend To Reinvent To Reuse Than Reuse )를 읽었으며 , 누군가 목록에 추가 된 것이 있는지 볼 것이라고 생각했습니다.


사람들은 추악하고 실패 할 수밖에없는 다음을 사용하는 경향이 있습니다.

string path = basePath + "\\" + fileName;

더 좋고 안전한 방법 :

string path = Path.Combine(basePath, fileName);

또한 파일에서 모든 바이트를 읽는 사용자 지정 메서드를 작성하는 사람들을 보았습니다. 이것은 매우 편리합니다.

byte[] fileData = File.ReadAllBytes(path); // use path from Path.Combine

으로 TheXenocide는 지적, 동일 적용 File.ReadAllText()File.ReadAllLines()


String.IsNullOrEmpty()


Path.GetFileNameWithoutExtension(string path)

확장자없이 지정된 경로 문자열의 파일 이름을 반환합니다.

Path.GetTempFileName()

디스크에 고유 한 이름의 0 바이트 임시 파일을 만들고 해당 파일의 전체 경로를 반환합니다.


System.Diagnostics.Stopwatch클래스입니다.


String.Format.

내가 본 횟수

return "£" & iSomeValue

보다는

return String.Format ("{0:c}", iSomeValue)

또는 백분율 기호를 추가하는 사람들-그런 것.


Enum.Parse ()


String.Join () (그러나 거의 모든 사람이 string.Split에 대해 알고 있으며 기회가있을 때마다 사용하는 것 같습니다 ...)


사용자의 컴퓨터에서 내 문서가 어디에 있는지 파악하려고합니다. 다음을 사용하십시오.

string directory =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

최근에 Windows 응용 프로그램에서 일부 파일을 다운로드해야했습니다. WebClient 개체에서 DownloadFile 메서드를 찾았습니다.

    WebClient wc = new WebClient();
    wc.DownloadFile(sourceURLAddress, destFileName);

/를 디렉토리 조작 문자열로 하드 코딩하는 것과 사용하는 것 :

IO.Path.DirectorySeparatorChar

의 StringBuilder 클래스와 특히 방법 AppendFormat .

추신 : String Operations 성능 측정을 찾고 있다면 : StringBuilder vs. String / Fast String Operations with .NET 2.0


Environment.NewLine

Guid로 파일 이름을 생성하는 대신 다음을 사용하십시오.

Path.GetRandomFileName()

많은 새로운 Linq 기능은 매우 알려지지 않은 것 같습니다.

Any<T>() & All<T>()

if( myCollection.Any( x => x.IsSomething ) )
    //...

bool allValid = myCollection.All( 
    x => x.IsValid );

ToList<T>(), ToArray<T>(), ToDictionary<T>()

var newDict = myCollection.ToDictionary(
    x => x.Name,
    x => x.Value );

First<T>(), FirstOrDefault<T>()

return dbAccessor.GetFromTable( id ).
    FirstOrDefault();

Where<T>()

//instead of
foreach( Type item in myCollection )
    if( item.IsValid )
         //do stuff

//you can also do
foreach( var item in myCollection.Where( x => x.IsValid ) )
    //do stuff

//note only a simple sample - the logic could be a lot more complex

All really useful little functions that you can use outside of the Linq syntax.



System.Text.RegularExpressions.Regex


See Hidden .NET Base Class Library Classes


For all it's hidden away under the Microsoft.VisualBasic namespace, TextFieldParser is actually a very nice csv parser. I see a lot of people either roll their own (badly) or use something like the nice Fast CSV library on Code Plex, not even knowing this is already baked into the framework.


input.StartsWith("stuff") instead of Regex.IsMatch(input, @"^stuff")


File stuff.

using System.IO;

File.Exists(FileNamePath)

Directory.Exists(strDirPath)

File.Move(currentLocation, newLocation);

File.Delete(fileToDelete);

Directory.CreateDirectory(directory)

System.IO.FileStream file = System.IO.File.Create(fullFilePath);

System.IO.File.ReadAllText vs writing logic using a StreamReader for small files.

System.IO.File.WriteAllText vs writing logic using a StreamWriter for small files.


Many people seem to like stepping through an XML file manually to find something rather than use XPathNaviagator.


Most people forget that Directory.CreateDirectory() degrades gracefully if the folder already exists, and wrap it with a pointless, if (!Directory.Exists(....)) call.


myString.Equals(anotherString)

and options including culture-specific ones.

I bet that at least 50% of developers write something like: if (s == "id") {...}


Path.Append is always forgotten in stuff I have seen.

ReferenceURL : https://stackoverflow.com/questions/178524/most-useful-net-utility-classes-developers-tend-to-reinvent-rather-than-reuse

반응형