C#
[C#] Cannot deconstruct dynamic object 해결하기
Minius
2022. 7. 26. 09:22
반응형
dynamic 형식을 하나 받아서 여러가지 변수를 한 메소드 안에서 만드려고 하니
Cannot deconstruct dynamic object 와 같은 에러가 떴다.
모두 영어로 검색 결과가 뜨길래 한국어 결과로 하나 나오게 해보자며 쓴다.
방법은 2가지가 있다.
1. Casting
class Deconstruct
{
static void Main()
{
dynamic d = new Test();
// Variables we want to deconstruct into
string text;
int number;
// Approach 1: Casting
(text, number) = ((string, int)) d.Method();
}
public (string, int) Method() => ("text", 5);
}
변수는 이전에 선언을 먼저 하고, 이후에 변수에 값을 넣을 때 casting을 해주는 방식이다.
((string, int))와 같이 캐스팅을 해서 형식을 맞춰준다.
2. Assign to a tuple variable first
class Test
{
static void Main()
{
dynamic d = new Test();
// Variables we want to deconstruct into
string text;
int number;
// Approach 2: Assign to a tuple variable first
(string, int) tuple = d.Method();
(text, number) = tuple;
}
public (string, int) Method() => ("text", 5);
}
tuple이라는 하나의 변수에 먼저 담고, 그걸 각 변수에 넣을 수 있도록 해준다.
원래 생각했던 것과 달리, 하나, 둘 정도의 과정이 더 필요한 것이다.
그래도 이렇게 해결이 되니 다행이다.
Cannot deconstruct dynamic object while calling dll's method
Say I have some dll with a method like so: public (string, List<string>) MyMethod(NameValueCollection Settings, MyClass1 params) { //do something return (result, errorList); } Now from my...
stackoverflow.com