인수로 C # 전달 함수
C #에서 수치 차별화를 수행하는 함수를 작성했습니다. 다음과 같이 보입니다 :
public double Diff(double x)
{
double h = 0.0000001;
return (Function(x + h) - Function(x)) / h;
}
다음과 같이 모든 기능을 전달할 수 있기를 원합니다.
public double Diff(double x, function f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
나는 이것이 위임에 가능하다고 생각하지만 (어쩌면?) 사용 방법을 잘 모르겠습니다.
도움을 주시면 감사하겠습니다.
위에서 언급 한 기능을 사용하면 작동하지만 동일한 작업을 수행하고 명명 내에서 의도를 정의하는 대리인도 있습니다.
public delegate double MyFunction(double x);
public double Diff(double x, MyFunction f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}
public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}
.Net (v2 이상)에는 대리자로 함수를 쉽게 전달할 수있는 몇 가지 일반 유형이 있습니다.
리턴 유형이있는 함수의 경우 Func <>가 있고 리턴 유형이없는 함수의 경우 Action <>이 있습니다.
Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).
So you can declare your Diff function to take a Func:
public double Diff(double x, Func<double, double> f) {
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:
double result = Diff(myValue, Function);
You can even write the function in-line with lambda syntax:
double result = Diff(myValue, d => Math.Sqrt(d * 3.14));
public static T Runner<T>(Func<T> funcToRun)
{
//Do stuff before running function as normal
return funcToRun();
}
Usage:
var ReturnValue = Runner(() => GetUser(99));
참고URL : https://stackoverflow.com/questions/3622160/c-sharp-passing-function-as-argument
'development' 카테고리의 다른 글
안드로이드에서 프로그래밍 방식으로 파일을 압축 해제하는 방법은 무엇입니까? (0) | 2020.07.14 |
---|---|
CSS 텍스트 변환으로 모든 대문자 사용 (0) | 2020.07.14 |
자바 스크립트-다른 배열을 기준으로 배열 정렬 (0) | 2020.07.14 |
'합성 속성 @panelState를 찾았습니다. (0) | 2020.07.14 |
값 목록과 비교하여 변수 평등 확인 (0) | 2020.07.14 |