2017-04-14 2 views
0
public static int getInfo(string info) 
    { 
     string inputValue; 
     int infor; 
     Console.WriteLine("Information of the employee: {0}", info); 
     inputValue = Console.ReadLine(); 
     infor = int.Parse(inputValue); 
     return infor; 

    } 

위 코드에서 사람의 이름 (문자열) 및 급여 (int)는 어떻게 얻을 수 있습니까? 사양은 정보 검색을 위해 메서드를 두 번 호출해야한다는 것입니다.동일한 메소드에서 문자열 및 정수 반환

+0

그래서 문자열이나 int 중 하나를 반환하는 방법을 원하십니까? –

+2

C# 7 + 튜플 사용 : https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/#user-content-tuples. –

+1

이것은 XY 문제를 비명을 지른다. (그것이 의미하는 것이 무엇인지 모른다면, 구글 그것, 나는 모바일에 편리한 링크가 없다). 이걸로 무엇을 이루려고합니까? –

답변

5

당신이 정보의 보유 클래스와 급여

public static int getInfo(string info,int salary) 

을 만들거나 클래스를 만드는 경우는 개별적으로 또는 더 잘 전달할 수

public class MyInfo 
    { 
     public int info { get; set; } 
     public int salary { get; set; } 

    } 

및 메소드 서명으로 간다,

public static int getInfo(MyInfo info) 

문자열과 int를 모두 반환하려면 다음과 같이 메소드 서명을 변경하는 것이 좋습니다. 타입 클래스 MyInfo

public static MyInfo getInfo(MyInfo info) 
+1

나는 OP가 자신의 방법으로 정보를 되찾고 싶어한다고 생각한다. –

+0

@PieterWitvoet ok 그대로 편집했습니다. C#에서 금메달을 얻으려면 2 번 더! :) – Sajeetharan

+0

@Sajeetharan 2 더 많은 금메달을! 질투심 많은! 행운을 빕니다, 당신은 그것을 빨리 얻을 것입니다 – EpicKip

1

귀하는이 같은 두 값 튜플을 반환 할 수 있습니다 :

internal Tuple<int, string> GetBoth(string info) 
{ 
    string inputValue; 
    int infor; 
    Console.WriteLine("Information of the employee: {0}", info); 
    inputValue = Console.ReadLine(); 
    infor = int.Parse(inputValue); 
    return new Tuple<int, string>(infor, inputValue); 
} 

internal void MethodImCallingItFrom() 
{ 
    var result = GetBoth("something"); 
    int theInt = result.Item1; 
    string theString = result.Item2; 
} 
-1

왜 그냥 2의 크기의 문자열 배열을 반환 해달라고? 처음에 (배열 [0]) 문자열이 두 번째에 (배열 [0])를 INT가 ... 나는 희망

public static string[] GetInfo (string info) 

을 나는 당신의 질문을 이해 못했습니다 ^^

+0

다른 경우와 함께 TryParse를 사용하여이 작업을 수행 할 수 있지만이 경우 메서드를 두 번 호출해야합니다. : ( –

+0

u는 또한 'string stringname + Convert.ToString (int intname);'을 만들 수 있습니다. –

-1

당신은 하나 개의 운전 방식을 원하는 경우

public static Person getInfo(string info) 
{ 
    string inputName; 
    string inputSalary; 

    Console.WriteLine("Information of the employee: {0}", info); 

    Console.WriteLine("Name:"); 
    inputName = Console.ReadLine(); 

    Console.WriteLine("Salary:"); 
    inputSalary = Console.ReadLine(); 

    Person person = new Person(); 
    person.Name = inputName; 
    person.Salary = int.Parse(inputSalary); 
    return person; 

} 
-1

: 당신은

public class Person 
{ 
    public string Name {get; set;} 
    public decimal Salary {get; set;} 
} 

하고 함수가 될 것이다 사람 클래스를 생성하고 이름과 급여를 읽을 필요 D는 내가 제네릭을 사용, 다양한 유형의 정보를 반환합니다 :

public static T GetInfo<T>(string name); 

// This can be called as following: 
string name = GetInfo<string>("name"); 
int salary = GetInfo<int>("salary"); 

하지만 한 가지 문제,있다 : 우리의 방법은 모든 유형을 반환 할 수 동안, string을 반환 Console.ReadLine가. 문자열을 '대상'유형으로 어떻게 변환 할 수 있습니까? T을 확인하고 지원하려는 모든 유형에 대해 사용자 정의 논리를 작성할 수는 있지만, 번거롭고 번거 롭습니다. 이제

public static T GetInfo<T>(string name, Func<string, T> convert); 

// This can be called as following: 
string name = GetInfo<string>("name", s => s); 
int salary = GetInfo<int>("salary", int.Parse); 

어떻게 당신이 그 방법을 구현합니까 : 더 나은 솔루션은 호출자가 어떻게 특정 유형에 문자열을 변환하는 알고 약간의 기능에 전달할 수 있도록하는 것입니다?

public static T GetInfo<T>(string name, Func<string, T> convert) 
{ 
    Console.WriteLine("Please enter " + name); 
    string input = Console.ReadLine(); 
    return convert(input); 
} 

몇 가지 참고 사항 :

  • 유형 매개 변수는 종종 단지 T 명명 된,하지만 난 그게 도움이 그들에게 같은 TInfo 등 더 자세한 설명 이름을 제공하기 위해 찾을 수 있습니다.
  • 컴파일러에 형식을 추론 할 수있는 충분한 정보가 있으므로 <string><int> 부분을 두 번째 예제에서 생략 할 수 있습니다.
  • 예제를 짧고 단순하게 유지하기 위해 오류 처리를 남겨 두었습니다.프로덕션 코드에서는 잘못된 입력을 처리하기위한 전략을 생각해 내야합니다.
0
public static void Main(string[] args) 
    { 
     string eName, totalSales; 
     double gPay, tots, fed, sec, ret, tdec,thome; 
     instructions(); 
     eName = getInfo("Name"); 
     totalSales = getInfo("TotalSales"); 
     tots = double.Parse(totalSales); 
     gPay = totalGpay(tots); 

}

public static string getInfo(string info) 
    { 
     string inputValue; 
     Console.WriteLine("Information of the employee: {0}", info); 
     inputValue = Console.ReadLine(); 

     return inputValue; 

    } 

이 필요했습니다 것입니다. 너희들이 언급 한 다른 속임수로 할 수 있었을거야. 아무튼 감사 해요.

관련 문제