태그(tag)로 찾기, 비교하기
유니티의 스크립트(script)에서 자신과 상속관계에 있지 않은
하이어라키(hierarchy)에 있는 오브젝트 들을
찾아 사용 하는 것도 가능하다.
GameObject test1 = GameObject.Find("오브젝트 네임"); //오브젝트 이름으로 찾기
GameObject test2 = GameObject.FindGameObjectWithTag("태그 네임"); //태그로 찾기. 단일 반환
GameObject[] test3 = GameObject.FindGameObjectsWithTag("태그 네임"); //태그로 찾기. 복수 반환.
그렇다면 오브젝트 네임으로 찾아 가져오게 된
GameObject는 원하는 태그로 되어있는지 어떻게 비교해야할까?
if(test1.tag == "test") 와 같이 string 비교도 가능하다.
하지만 string비교는 불필요한 리소스를 잡아 먹어 비효율적이다.
if(test1.CompareTag("test")) 와 같이 유니티에서 만들어 놓은 비교 함수를 권장한다.
'공부 > Unity' 카테고리의 다른 글
GameObject 삭제, 활성, 비활성화 (0) | 2016.05.20 |
---|---|
[잡담]유니티를 일주일정도 공부 하면서 드는 생각 (0) | 2016.05.19 |
유니티 프로젝트 폴더 백업 방법 (1) | 2016.05.13 |
[잡담]유니티 첫 공부 소감 (0) | 2016.05.12 |
유니티 공부 시작 - 자습 방법 (0) | 2016.05.12 |
유니티 프로젝트 폴더 백업 방법
유니티는 프로젝트를 만들 때
별도로 WorkSpace가 생기지 않는다.
프로젝트를 Open할 때에도
파일이 아닌 폴더를 지정하여 불러온다.
그렇다고 폴더를 통째로 복사하기에는 용량이 꽤 된다.
Library 같은 경우는 다시 만들어 주므로
유니티 설정을 통해 최소화 시켜보자.
1. Edit -> Project Settings -> Editor 에서
Version Control Mode를 Visible Meta Files 로 바꾸고
Asset Serialization Mode를 Force Text 로 바꾼다.
종료...
2. 이제 Assets에 Meta파일이 같이 생기고 아래의 2폴더만 백업을 해둔다.
3. Unity를 실행하여 폴더를 잡아 Open하면
Project의 오브젝트들은 그대로이지만
Hierarchy는 기본 값으로 되어있다.
Open Scene을 해주면 된다.
4. 자신이 만든 Scene(파일 명.unity)을 불러오자. 보통 Assets폴더에 저장해 두거나 그 아래에 Scene폴더를 둘것 이다.
5. 불러오면 Hierarchy에 설정했던 것들이 다시 보이게 된다.
//끝.
'공부 > Unity' 카테고리의 다른 글
GameObject 삭제, 활성, 비활성화 (0) | 2016.05.20 |
---|---|
[잡담]유니티를 일주일정도 공부 하면서 드는 생각 (0) | 2016.05.19 |
태그(tag)로 찾기, 비교하기 (0) | 2016.05.19 |
[잡담]유니티 첫 공부 소감 (0) | 2016.05.12 |
유니티 공부 시작 - 자습 방법 (0) | 2016.05.12 |
Console 키입력 - Console.ReadKey, ConsoleKeyInfo
//Console 키입력
ConsoleKeyInfo cKey = Console.ReadKey(true); //bool 값은 입력된 값 표시 여부로 true 일 때 표시 안함이다.
//Console.ReadKey() 는 기본 false이다. 콘솔창에 표시된다.
switch (cKey.Key) //변수.Key로 어떤 키를 입력 했는지 알 수 있다.
{
//대략 아래처럼 ConsoleKey 를 가져와 처리한다.
case ConsoleKey.LeftArrow: //방향키 왼쪽
break;
case ConsoleKey.RightArrow: //방향키 오른쪽
break;
case ConsoleKey.UpArrow: //방향키 위쪽
break;
case ConsoleKey.DownArrow: //방향키 아래쪽
break;
}
//ConsoleKey는 enum으로 되어있다. 꽤 많으나 주석 처리가 잘되어있으니
//Visual Studio에서 F12를 눌러 필요한 것을 찾아보자.
'공부 > C#' 카테고리의 다른 글
소켓 통신, 웹 통신(간략 설명, 메모) (0) | 2016.05.28 |
---|---|
yield return, yield break (0) | 2016.05.24 |
예외처리 - try, catch, finally, throw new Exception (0) | 2016.05.12 |
파일 로드 - FileStream, StreamReader, ReadAllText, ReadAllLines (0) | 2016.05.12 |
파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines (0) | 2016.05.12 |
예외처리 - try, catch, finally, throw new Exception
//예외처리 - try, catch, finally
//예전에 java랑 Jsp 다룰때 꽤 많이 썼었다.(try, catch 안쓰면 컴파일 에러나는 것도 꽤 있었다.)
//쉽게 생각하자.
//try - 하다가 (문제가 없어야 되는게 맞지만) 문제가 생기면
//catch - 잡는다.(문제가 없으면 잡을 것도 없다.)
//finally - 마지막으로 문제가 있든 없든 실행할 코드 - 안써도 됨.
class ExceptionTest //일부러 에러 내보기 위한 class생성
{
public int i = 10;
}
class Program
{
//함수로 에러발생이 나게 만들어 보자 - 아래의 main함수 먼저 보고 돌아오자.
static void TestDiv(int n1, int n2)
{
if(n2==0)
{
//커스텀 Exception - 내가만든 에러 메세지
throw new Exception("n2는 0이 아니어야 한다.");
}
Console.WriteLine("n1 / n2 함수");
Console.WriteLine("{0} / {1} = {2}", n1, n2, n1 / n2);
}
//메인 함수
static void Main(string[] args)
{
ExceptionTest t = null;
//예외 처리
try
{
//위험 요소가 있는 코드를 작성
Console.WriteLine("Test : {0}", t.i);
}
catch (NullReferenceException e) //특정 예외만 골라내기 - new되지 않는 class사용하려고 함
{
//try 부분에서 에러가 발생하면 catch 소스로 접근
//프로그램을 죽이지 않고 처리하기 위한 방법
Console.WriteLine("널 참조 예외가 발생");
Console.WriteLine(e.Message); //한글로 간략 오류 설명
Console.WriteLine("=======================");
Console.WriteLine(e); //예외 메세지 전체
}
//catch를 여러개 사용할 수 있는데 위에서 먼저 잡히면 아래껀 무시
catch (Exception e) //모든 예외
{
//try 부분에서 에러가 발생하면 catch 소스로 접근
//프로그램을 죽이지 않고 처리하기 위한 방법
Console.WriteLine("예외가 발생함.");
Console.WriteLine(e.Message); //한글로 간략 오류 설명
//Console.WriteLine("=======================");
//Console.WriteLine(e); //예외 메세지 전체
}
finally
{
//예외가 발생 하든 안하든
//무조건 들어와서 실행되는 영역.
Console.WriteLine("try 마지막");
}
//0으로 나눌때 에러를 발생해보자
try
{
Console.WriteLine("10/0 = ?");
//int n1 = 10 / 0; //에러 - 0으로 나눌 수 없어서 빨간줄
int n1 = 10;
int n2 = 0;
//int n3 = n1 / n2;
//Console.WriteLine("{0} / {1} = {2}", n1, n2, n3);
TestDiv(n1, n2);
}
catch(DivideByZeroException e) //0으로 나눌때 잡는 Exception
{
Console.WriteLine("0으로 나누려고 함");
Console.WriteLine(e);
}
catch (Exception e)
{
Console.WriteLine("에러!!!!!!!");
Console.WriteLine(e);
}
//catch가 개발용...테스트 할 때 포함 하면 좋지만
//성능이 그리 좋은게 아니라
//배포시에는 뺄수 있으면 빼는 것이 좋다.
}
}
'공부 > C#' 카테고리의 다른 글
yield return, yield break (0) | 2016.05.24 |
---|---|
Console 키입력 - Console.ReadKey, ConsoleKeyInfo (0) | 2016.05.12 |
파일 로드 - FileStream, StreamReader, ReadAllText, ReadAllLines (0) | 2016.05.12 |
파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines (0) | 2016.05.12 |
컬렉션(Collection), 제네릭 컬렉션(Generic Collection) - 예) ArrayList, List<T> (0) | 2016.05.11 |
파일 로드 - FileStream, StreamReader, ReadAllText, ReadAllLines
//파일 로드 - FileStream, StreamReader, ReadAllText, ReadAllLines
//이전 글 - 파일 저장과 대입되는 4가지 방법 이다.
private string loadData; //로드한 데이터를 담을 변수
//디렉터리 경로 지정
private const string path = "./save/test1/"; //요즘 많이 사용하는 방법 /
private const string path2 = ".\\save\\test2"; //옛날부터 디렉터리 구분하는 방법 \\
private const string path3 = @".\save\test3"; //@뒤에 있는 string은 디렉터리를 표시하는 것이라고 지정 - 최신
private void PrintLoadData()
{
Console.WriteLine("읽은 데이터는 다음과 같습니다.");
Console.WriteLine("{0}\n", loadData);
}
//로드
//1. FileStream
public void LoadFromFileStream(string fileName = "S_FileString.txt")
{
string fullpath = path + "/" + fileName; //그냥 쉽게 하려고 쓴것이다. 성능은 StringBuilder이 좋다.
try
{
//파일 스트림 생성. cs파일 상단에 using System.IO; 추가
FileStream fs = new FileStream(
fullpath,
FileMode.Open,
FileAccess.Read);
//바이트 단위로 로드
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
loadData = Encoding.UTF8.GetString(bytes);
fs.Close();
}
//파일 못찾음
catch (FileNotFoundException) //변수 없어도 됨
{
Console.WriteLine("파일을 찾지 못했습니다.");
return;
}
//디렉터리 못찾음
catch(DirectoryNotFoundException)
{
Console.WriteLine("폴더가 없습니다.");
return;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("로딩 완료 LoadFromFileStream");
PrintLoadData();
}
//2. StreamReader
public void LoadFromStreamReader(string fileName = "S_StreamWriter.txt")
{
string fullpath = path2 + "/" + fileName;
try
{
FileStream fs = new FileStream(
fullpath,
FileMode.Open,
FileAccess.Read);
StreamReader sr = new StreamReader(fs); //스트림 생성
string line;
StringBuilder builder = new StringBuilder();
while((line = sr.ReadLine()) != null) //한줄 읽는데 null이 아니면
{
builder.Append(line); //한줄 저장
builder.Append("\n"); //개행
}
loadData = builder.ToString();
sr.Close();
fs.Close();
}
//파일 못찾음
catch (FileNotFoundException) //변수 없어도 됨
{
Console.WriteLine("파일을 찾지 못했습니다.");
return;
}
//디렉터리 못찾음
catch (DirectoryNotFoundException)
{
Console.WriteLine("폴더가 없습니다.");
return;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("로딩 완료 LoadFromStreamReader");
PrintLoadData();
}
//3. ReadAllText
public void LoadFromReadAllText(string fileName = "S_WriteAllText.txt")
{
string fullpath = path3 + "/" + fileName;
try
{
loadData = File.ReadAllText(fullpath); //걍 모두 저장. 한줄이라 참쉽다.
}
//파일 못찾음
catch (FileNotFoundException) //변수 없어도 됨
{
Console.WriteLine("파일을 찾지 못했습니다.");
return;
}
//디렉터리 못찾음
catch (DirectoryNotFoundException)
{
Console.WriteLine("폴더가 없습니다.");
return;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("로딩 완료 LoadFromReadAllText");
PrintLoadData();
}
//4. ReadAllLines
public void LoadFromReadAllLines(string fileName = "S_WriteAllLines.txt")
{
string fullpath = path2 + "/" + fileName;
try
{
string[] lines = File.ReadAllLines(fullpath); //라인별로 string 배열에 저장
StringBuilder builder = new StringBuilder(lines.Length); //스트링 변수의 크기를 알고 있으면 선언해주는게 좋다
foreach(var line in lines)
{
builder.Append(line);
builder.Append("\n");
}
loadData = builder.ToString();
}
//파일 못찾음
catch (FileNotFoundException) //변수 없어도 됨
{
Console.WriteLine("파일을 찾지 못했습니다.");
return;
}
//디렉터리 못찾음
catch (DirectoryNotFoundException)
{
Console.WriteLine("폴더가 없습니다.");
return;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("로딩 완료 LoadFromReadAllLines");
PrintLoadData();
}
'공부 > C#' 카테고리의 다른 글
Console 키입력 - Console.ReadKey, ConsoleKeyInfo (0) | 2016.05.12 |
---|---|
예외처리 - try, catch, finally, throw new Exception (0) | 2016.05.12 |
파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines (0) | 2016.05.12 |
컬렉션(Collection), 제네릭 컬렉션(Generic Collection) - 예) ArrayList, List<T> (0) | 2016.05.11 |
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 예제소스 (0) | 2016.05.11 |
파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines
//파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines
//4가지 방법
//string 1줄
private string saveData = "1.테스트\n2.진행중\r\n3.입니다.";
//\n 개행 \r 캐리지리턴 - 시스템마다 개행을 나타내는 문자가 달라서 적음 \r
//string배열
private string[] saveData2 = { "1.테스트", "2.진행중", "3.입니다." };
//디렉터리(폴더) 경로 지정
private const string path = "./save/test1/"; //요즘 많이 사용하는 방법 /
private const string path2 = ".\\save\\test2"; //옛날부터 디렉터리 구분하는 방법 \\
private const string path3 = @".\save\test3"; //@뒤에 있는 string은 디렉터리를 표시하는 것이라고 지정 - 최신
//1.FileStream
public void SaveByFileStream(string fileName = "S_FileString.txt")
{
StringBuilder fullPath = new StringBuilder();
fullPath.Append(path);
fullPath.Append("/");
fullPath.Append(fileName);
//string fullPath = path + "/" + fileName;
try
{
//상단에 using System.IO; 추가
FileStream fs = new FileStream(
fullPath.ToString(),
FileMode.Create,
FileAccess.Write);
//Byte단위로 바꾸어 주어야 함.
byte[] bytes = Encoding.UTF8.GetBytes(saveData); //string문자가 UTF8인코딩으로 byte화
fs.Write(bytes, 0, bytes.Length); //byte 저장. 0부터 총 길이만큼
fs.Close();
}
catch(DirectoryNotFoundException e)
{
Console.WriteLine("디렉터리가 없습니다. 생성합니다.");
Directory.CreateDirectory(path);
SaveByFileStream(fileName);
return;
}
catch(Exception e)
{
Console.WriteLine(e);
return;
}
Console.WriteLine("세이브 완료(SaveByFileStream)");
}
//2.StreamWriter
public void SaveByFileStreamWriter(string fileName = "S_StreamWriter.txt")
{
StringBuilder fullPath = new StringBuilder();
fullPath.Append(path2);
fullPath.Append("/");
fullPath.Append(fileName);
try
{
//상단에 using System.IO; 추가
FileStream fs = new FileStream(
fullPath.ToString(),
FileMode.Create,
FileAccess.Write);
StreamWriter sw = new StreamWriter(fs); //스트림을 만들어서
sw.WriteLine(saveData); //일괄 저장
sw.Close();
fs.Close();
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("디렉터리가 없습니다. 생성합니다.");
Directory.CreateDirectory(path2); //디렉터리 생성
SaveByFileStreamWriter(fileName); //자기 자신 다시 부름
return; //함수 종료
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
Console.WriteLine("세이브 완료(SaveByFileStreamWriter)");
}
//3.WriteAllText
public void SaveByWriteAllText(string fileName = "S_WriteAllText.txt")
{
StringBuilder fullPath = new StringBuilder();
fullPath.Append(path3);
fullPath.Append("/");
fullPath.Append(fileName);
//string fullPath = path + "/" + fileName;
try
{
File.WriteAllText(fullPath.ToString(), saveData); //핵심 - string 통째로 저장
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("디렉터리가 없습니다. 생성합니다.");
Directory.CreateDirectory(path3); //디렉터리 생성
SaveByWriteAllText(fileName); //자기 자신 다시 부름
return; //함수 종료
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
Console.WriteLine("세이브 완료(SaveByWriteAllText)");
}
//4.WriteAllLines
public void SaveByWriteAllLines(string fileName = "S_WriteAllLines.txt")
{
StringBuilder fullPath = new StringBuilder();
fullPath.Append(path2);
fullPath.Append("/");
fullPath.Append(fileName);
//string fullPath = path + "/" + fileName;
try
{
File.WriteAllLines(fullPath.ToString(), saveData2); //핵심 - string 배열 저장
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("디렉터리가 없습니다. 생성합니다.");
Directory.CreateDirectory(path2); //디렉터리 생성
SaveByWriteAllLines(fileName); //자기 자신 다시 부름
return; //함수 종료
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
Console.WriteLine("세이브 완료(SaveByWriteAllLines)");
}
//짧은게 쓰기에는 편하지만 준비과정이 길고 쓰기 불편하게 성능은 더 좋지 않을 까 한다.
'공부 > C#' 카테고리의 다른 글
예외처리 - try, catch, finally, throw new Exception (0) | 2016.05.12 |
---|---|
파일 로드 - FileStream, StreamReader, ReadAllText, ReadAllLines (0) | 2016.05.12 |
컬렉션(Collection), 제네릭 컬렉션(Generic Collection) - 예) ArrayList, List<T> (0) | 2016.05.11 |
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 예제소스 (0) | 2016.05.11 |
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 개념 (0) | 2016.05.11 |
[잡담]유니티 첫 공부 소감
정~~~말 쉽게 3D프로그래밍을 할 수 있게
잘 만들어진 엔진 툴인거 같다.
DirectX로 게임 하나 만들 때에는
Vector3하나부터 갖가지 Matrix 변수들까지
신경 써줄게 많았는데
Unity는 오브젝트 생성이나 각각의
world의 location, scale, pos컨트롤
메테리얼 적용,
카메라 컨트롤,
충돌 함수, 조명,
심지어 셰이더로 어렵게 써야하는 그림자 까지
유니티는 그냥 된다.
말 그대로 기본적으로 되어있더라.....그냥이다...그냥...
정말 크나큰 감동이다.
아예 쌩초보자가 보기에는
위의 설명들도 어려울수 있겠고
Unity 자습서동영상을 봐도
뭔말인가 싶겠지만
DirectX에서 3D의 개념을 공부하고
익힌 사람이라면(게임 좀 쟈기가 만들어 봤다면)
Unity는 정말 쉬운 툴이다.
이렇게 첫 초행길에 감동을 받았는데
앞으로 중, 고급 스킬을 익힐 때는 어떨지 기대가 된다.
'공부 > Unity' 카테고리의 다른 글
GameObject 삭제, 활성, 비활성화 (0) | 2016.05.20 |
---|---|
[잡담]유니티를 일주일정도 공부 하면서 드는 생각 (0) | 2016.05.19 |
태그(tag)로 찾기, 비교하기 (0) | 2016.05.19 |
유니티 프로젝트 폴더 백업 방법 (1) | 2016.05.13 |
유니티 공부 시작 - 자습 방법 (0) | 2016.05.12 |
유니티 공부 시작 - 자습 방법
유니티는 책이 있으면 좋지만
책 없이도 유니티 홈페이지 제공하는 자습 공간이 있어
누구나 쉽게 접근 하고 배울 수 있다. - 인터넷만 되면 된다.
심지어 동영상으로 되어있고 한글 자막이 달린 것도 있다.
1. 위의 홈페이지 주소에 접근하자.
2. 홈페이지 상단의 교육 자료를 클릭
3. 자습서 메뉴를 클릭
4. 엔진 부분의 프로젝트에서 보고 싶은 것을 클릭
5. Introdution은 소개니까 굳이 안봐도 되고 아래부터 하나씩 보기
// 모두 한글 자막이 있으면 좋지만 후반 부로 갈 수록 자막이 없는 것도 나온다.
// 그럴 땐 동영상을 보면서 단어의 키포인트를 잡아 따라해보자.
'공부 > Unity' 카테고리의 다른 글
GameObject 삭제, 활성, 비활성화 (0) | 2016.05.20 |
---|---|
[잡담]유니티를 일주일정도 공부 하면서 드는 생각 (0) | 2016.05.19 |
태그(tag)로 찾기, 비교하기 (0) | 2016.05.19 |
유니티 프로젝트 폴더 백업 방법 (1) | 2016.05.13 |
[잡담]유니티 첫 공부 소감 (0) | 2016.05.12 |
컬렉션(Collection), 제네릭 컬렉션(Generic Collection) - 예) ArrayList, List<T>
//컬렉션(Collection), 제네릭 컬렉션(Generic Collection)
//가장 큰 차이점
//컬렉션은 아무거나 잡다하게 다 집어 넣어 사용 할 수 있고
//제네릭 컬렉션은 제네릭 타입<T>을 집어넣어 해당 타입만 컨트롤 하는 것이다.
//안정성이나 속도 면에서 제네릭 컬렉션이 좋다.
//컬렉션 - 템플릿 없음
//상단에 using System.Collections; 추가
ArrayList array = new ArrayList(); //std::vector 비슷한 녀석
array.Add(10);
array.Add(20);
array.Add(15.5f);
array.Add("가나다");
array.Add(c1);
array.Add(s1); //struct는 박싱이 일어난다.
//자료형이나 class, struct 구분없이 전부 다 들어갈 수 있다.
for (int i = 0; i < array.Count; ++i )
{
Console.WriteLine(array[i]);
}
Console.WriteLine();
//그외
//HashTable //std::map 과 비슷
//Queue
//Stack
//===================================================//
//제네릭 컬렉션 - <T> 템플릿 형식
//std::vector<T> 같은 녀석
List<int> numList = new List<int>(); //타입이 지정되어야 한다.
numList.Add(19);
numList.Add(30);
numList.Add(54);
//numList.Add(1.15); //타입이 안맞아 에러
foreach(int node in numList)
{
Console.Write(node + " ");
}
Console.WriteLine();
//std::list<> 같은 녀석
LinkedList<int> linked = new LinkedList<int>();
linked.AddLast(50);
linked.AddLast(60);
linked.AddLast(70);
linked.AddFirst(40);
foreach (int node in linked)
{
Console.Write(node + " "); // 40 50 60 70
}
Console.WriteLine();
//그외
//Dictionary<key, value> //std::map
//Queue<T>
//Stack<T>
'공부 > C#' 카테고리의 다른 글
파일 로드 - FileStream, StreamReader, ReadAllText, ReadAllLines (0) | 2016.05.12 |
---|---|
파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines (0) | 2016.05.12 |
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 예제소스 (0) | 2016.05.11 |
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 개념 (0) | 2016.05.11 |
정렬 Array.Sort, Array.Reverse (0) | 2016.05.10 |
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 예제소스
//struct (구조체) 생성
//가비지 컬렉팅의 대상이 아니고
//스택메모리에 할당되는 struct
struct MyStruct
{
//구조체에서는 미리 할당이 안됨. class에서는 됨.
//public int i = 10; //에러 - 구조체에는 인스턴스 필드 이니셜라이저를 사용할 수 없습니다.
public int i;
public int j;
//struct에서도 생성자를 몇가지 조건하에 만들 수있다.
//1. 매개변수가 무조건 있을 것
//2. 생성자 안에서 struct의 변수에 값을 모두 할당할 것
//매개변수가 없는 생성자는 불가
//public MyStruct()
//{
//}
public MyStruct(int num1, int num2) //인자 수가 꼭 변수 수에 맞추는 것은 아니다.
{
i = num1;
j = num2; //하나만 해도 안되고 변수 모두에 값을 할당해야 한다.
}
//함수는 그냥 만들 수 있다.
public void Show()
{
Console.WriteLine("i : {0}, j : {1}", i, j);
}
}
//class생성
class MyClass
{
public int i = 10;
public void Show()
{
Console.WriteLine("MyClass i : {0}", i);
}
public override string ToString()
{
//return base.ToString(); //base는 부모 타입. object
return base.ToString() +"는 i가 " + i + "입니다";
}
public override bool Equals(object obj)
{
//as로 캐스팅
MyClass other = obj as MyClass;
if(other != null)
{
if(other.i == this.i)
{
return true;
}
}
return false;
}
}
static void Func1(object o)
{
MyClass my = o as MyClass;
if(my != null)
{
my.Show();
}
{
Console.WriteLine("MyClass가 아니다." + o.ToString() + "입니다");
}
//메인 함수
static void Main(string[] args)
{
//MyStruct s1; //에러 - 할당 되지 않은 것은 사용 할 수 없다.
//s1.Show();
MyStruct s1 = new MyStruct(); //기본 생성자, 안만들어도 자동으로 있다.
s1.Show();
MyStruct s2; //생성 없이 사용 방법
s2.i = 5; //변수에 모두 값을 할당 한다.
s2.j = 6;
s2.Show(); //그러면 new없이 사용 가능 하다.
MyStruct s3 = new MyStruct(100, 200); //별도의 생성자로 할당
s3.Show();
MyStruct s4 = s2; //class같은 경우는 heap메모리에서
//같은 것을 참조하지만
s2.i++; //struct에서는 값 복사를 한다.(별개로 복사, 깊은 복사)
s2.Show();
s4.Show(); //결과가 다르다
//class 할당
MyClass c1 = new MyClass(); //class는 무조건 new로 heap에 할당
Console.WriteLine(c1.ToString()); //class 는 object 타입을 기본적으로 상속 받는다.
MyClass c2 = new MyClass();
c2.i = 10;
if(c1 == c2) //class는 ==로 비교하면 주소값을 비교 한다.
{
Console.WriteLine("c1과 c2는 같다.");
}
else
{
Console.WriteLine("c1과 c2는 다르다."); //주소값이 다르기 떄문에 false
}
//비교함수 재정의 하여 처리
if (Object.Equals(c1, c2)) //MyClass의 public override bool Equals(object obj) 를 탄다.
{
Console.WriteLine("c1과 c2는 같다."); //i값이 같아서 true
}
else
{
Console.WriteLine("c1과 c2는 다르다.");
}
//object;
//박싱언박싱(Boxing, Unboxing)
//class나 struct나 기본적으로 object class를 상속받고 있어
//object를 인자로 받는 함수에 인자로 들어 갈 수 있다.
Func1(c1); //class는 같은 heap 메모리에서 참조만 넘겨준다.
Func1(s1); //구조체를 object로 받으면 heap에 new 로 새로 생성된다.(본체는 stack에 남아있다.)
//메모리 낭비. 복사체는 가비지컬렉터 기다림.
Object obj = s1; //박싱이 일어남.(stack에 있는 struct가 object 클래스에 들어가야 하므로 Stack에서 Heap으로 모두 복사된다.)
MyStruct s5 = (MyStruct)obj; //언박싱(heap에 있는걸 Stack에 복사한다. 매우 리소스를 까먹으므로 안좋다.)
//int, float같은 기본 형은 다 struct이다.
string str1 = "abc";
string str2 = "abc";
if(str1 == str2)
{
//class 타입은 주소값을 비교한다. 하지만...
//string은 class 타입이지만
//너무 자주 사용되기에 이미 값비교로 override 되어있다.
Console.WriteLine("str1 == str2는 참이다."); //참으로 나온다.
}
else
{
Console.WriteLine("str1 == str2는 거짓이다.");
}
}
'공부 > C#' 카테고리의 다른 글
파일 저장 - FileStream, StreamWriter, WriteAllText, WriteAllLines (0) | 2016.05.12 |
---|---|
컬렉션(Collection), 제네릭 컬렉션(Generic Collection) - 예) ArrayList, List<T> (0) | 2016.05.11 |
C#에서의 struct(구조체)와 class - 메모리 구조 차이, Boxing, Unboxing 개념 (0) | 2016.05.11 |
정렬 Array.Sort, Array.Reverse (0) | 2016.05.10 |
추상 클래스, 추상 함수(abstract), 인터페이스(interface) (0) | 2016.05.09 |