2012-06-04 3 views
1

저는 C#을 처음 사용했습니다. 명령 줄 인수에 문제가 있습니다. 내가하고 싶은 것은 세 번째 cmd 라인 인수를 사용하고 그것에 쓰는 것이다. 내가 쓰고 싶은 파일의 경로와 다른 것들을 지정했다. 하지만 여기서 질문은 사용자 정의 함수에서 명령 줄 인수 (예 : args [3])에 액세스 할 수 있습니까? 우리는 어떻게해야할까요? 아래 코드는 내 코드입니다.C#의 명령 줄 인수

public class Nodes 
{ 
public bool isVisited; 
public string parent; 
public string[] neighbour; 
public int nodeValue; 

public Nodes(string[] arr, int nodeValue) 
{ 
    this.neighbour = new string[arr.Length]; 
    for (int x = 0; x < arr.Length; x++) 
     this.neighbour[x] = arr[x];//hi...works?? 
    this.isVisited = false; 
    this.nodeValue = nodeValue; 
} 


} 

public class DFS 
{ 
static List<string> traversedList = new List<string>(); 

static List<string> parentList = new List<string>(); 
static BufferBlock<Object> buffer = new BufferBlock<object>(); 
static BufferBlock<Object> buffer1 = new BufferBlock<object>(); 
static BufferBlock<Object> buffer3 = new BufferBlock<object>(); 
static BufferBlock<Object> buffer2 = new BufferBlock<object>(); 

public static void Main(string[] args) 
{ 

    int N = 100; 
    int M = N * 4; 
    int P = N * 16; 

    Stopwatch stopwatch = new Stopwatch(); 
    stopwatch.Start(); 

    List<string> global_list = new List<string>(); 


    StreamReader file = new StreamReader(args[2]); 

    string text = file.ReadToEnd(); 

    string[] lines = text.Split('\n'); 


    string[][] array1 = new string[lines.Length][]; 
    Nodes[] dfsNodes = new Nodes[lines.Length]; 

    for (int i = 0; i < lines.Length; i++) 
    { 
     lines[i] = lines[i].Trim(); 
     string[] words = lines[i].Split(' '); 

     array1[i] = new string[words.Length]; 
     dfsNodes[i] = new Nodes(words, i); 
     for (int j = 0; j < words.Length; j++) 
     { 
      array1[i][j] = words[j]; 
     } 
    } 
    StreamWriter sr = new StreamWriter(args[4]); 

    int startNode = int.Parse(args[3]); 

    if (args[1].Equals("a1")) 
    { 
     Console.WriteLine("algo 0"); 
     buffer.Post(1); 
     dfs(dfsNodes, startNode, "root"); 
    } 
    else if (args[1].Equals("a2")) 
    { 
     Console.WriteLine("algo 1"); 
     buffer1.Post(1); 
     dfs1(dfsNodes, startNode, "root",sr); 
    } 
    else if (args[1].Equals("a3")) 
    { 
     buffer3.Post(1); 
     List<string> visitedtList = new List<string>(); 
     Console.WriteLine("algo 2"); 
     dfs2(dfsNodes, startNode, "root", visitedtList,sr); 
    } 

    stopwatch.Stop(); 

    Console.WriteLine(stopwatch.Elapsed); 
    Console.ReadLine(); 
} 

public static void dfs(Nodes[] node, int value, string parent,StreamWriter sr1) 
{ 
    int id = (int)buffer.Receive(); 
    sr1=new StreamWriter(arg 
    Console.WriteLine("Node:" + value + " Parent:" + parent + " Id:" + id); 
    sr1.Write("Node:" + value + " Parent:" + parent + " Id:" + id); 
    id++; 
    traversedList.Add(value.ToString()); 
    buffer.Post(id); 
    for (int z = 1; z < node[value].neighbour.Length; z++) 
    { 
     if (!traversedList.Contains(node[value].neighbour[z])) 
     { 
      dfs(node, int.Parse(node[value].neighbour[z]), value.ToString(),sr1); 
     } 

    } 
    return; 



} 

public static void dfs1(Nodes[] node, int value, string parent, StreamWriter sr) 
{ 
    int id = (int)buffer1.Receive(); 
    sr.Write("Node:" + value + " Parent:" + parent + " Id:" + id); 
    node[value].isVisited = true; 
    node[value].parent = parent; 
    id++; 
    buffer1.Post(id); 
    for (int z = 1; z < node[value].neighbour.Length; z++) 
    { 
     buffer2.Post(node[int.Parse(node[value].neighbour[z])]); 
     if (!isVisited()) 
     { 
      dfs1(node, int.Parse(node[value].neighbour[z]), value.ToString(),sr); 
     } 

    } 
    return; 



} 

public static void dfs2(Nodes[] node, int value, string parent, List<string> visitedtList, StreamWriter sr) 
{ 
    int id = (int)buffer3.Receive(); 
    sr.Write("Node:" + value + " Parent:" + parent + " Id:" + id); 
    id++; 
    visitedtList.Add(value.ToString()); 
    buffer3.Post(id); 
    for (int z = 1; z < node[value].neighbour.Length; z++) 
    { 
     buffer2.Post(node[int.Parse(node[value].neighbour[z])]); 
     if (!visitedtList.Contains(node[value].neighbour[z])) 
      dfs2(node, int.Parse(node[value].neighbour[z]), value.ToString(), visitedtList,sr); 

    } 
    return; 



} 

public static bool isVisited() 
{ 
    Nodes node = (Nodes)buffer2.Receive(); 
    return node.isVisited; 
} 

} 

그래서 각 dfs의 출력을 명령 줄 인수로 지정된 파일에 기록하고 싶습니다. 그렇다면 dfs, dfs1 메소드의 args에 액세스 할 수 있습니까 ??? 고맙습니다.

답변

3

글쎄, 가장 간단한 형태로, 그냥 사용하는 저장 나중에

class Program 
{ 
    static string _fpath; 
    static void Main(string[] args) 
    { 
     // ...stuff 
     _fpath = args[3]; 
    } 

    static void WriteFile() 
    { 
     using(var stream = File.Open(_fpath, ...)) 
     { 
      // write to file 
     } 
    } 
} 

반드시 그렇지는 정확히 내가 그것을 할 것입니다,하지만 당신은 아이디어를 얻을 방법에 대해 설명합니다. D : 당신은 단순히

this.neighbour = arr; 

아, 관리 코드의 경이로움을 쓸 수

this.neighbour = new string[arr.Length]; 
for (int x = 0; x < arr.Length; x++) 
    this.neighbour[x] = arr[x];//hi...works?? 

코드의이 비트에 관한 또한

.... 두 번째 배열로 요소를 복사 할 필요가 없습니다. 물론, 인수 배열 (arr)의 요소에 대한 변경 사항이 내부 배열에 반영된다는 사실을 고려해야합니다.

+0

당신은 file.open에 try {} catch {} 블록이 없습니다. –

+4

@ColeJohnson : 예, 그리고'_fpath'는 null이 될 수 있습니다. 사용자는 충분한 인수를주지 않았을 수 있으며' args [3]','_fpath'는 런타임에 변경 될 수 있기 때문에 런타임에 수정할 수 있습니다. 메서드에서 정적 필드를 사용하는 대신 경로를'WriteFile'에 대한 인수로 전달하는 것이 좋습니다. , 개념의 예. 실제 응용 프로그램에서 발생하는 오류 처리 코드로 복잡하게 처리 할 필요가 없습니다. 그것은 구현 자의 몫입니다. –

+0

@ColeJohnson : 문제의 일부는 아니지만 문제는 아닙니다. – Ryan

2

"숨겨진"방법으로 함수를 전달하는 대신 함수에 인수를 전달하는 것이 좋습니다.

정적 변수와 GetCommandLineArgs는 숨겨진 방법으로 다른 변수를 전달할 때 유용합니다 (다른 답변에서 지적한 것처럼). 단점은 (정적 공유 의존성을 설정해야하기 때문에) 테스트하기가 더 어렵고, 숨겨진 의존성이 미래의 독자에게는 덜 명확합니다.

+0

입력 녀석을 주셔서 감사하지만 매개 변수로 함수에 인수를 전달하려고 할 때 args [4]를 사용하여 함수 내부에서 액세스하려고하면 프로세스가 다른 프로세스에서 사용 된 이후로 파일에 액세스 할 수 없다는 오류가 발생합니다. –

+1

파일이 잠긴 경우 인수를 전달하는 방법은 중요하지 않습니다. 여전히 잠금 상태가됩니다 ... –

+0

oops..my bad !! 그 일하는 지금 .. 당신의 도움에 감사드립니다. –