2016-08-24 2 views
1

내가 얻으려고하는 것은 동적으로 "필터"변수를 초기화하는 것입니다.동적으로 var 필터 초기화

  • null로 초기화하면 오류가 발생합니다.
  • 비워두면 오류가 발생합니다.

    var filter=null; 
    
    if (id != 0) 
        if (subID != 0) 
         //Get Specific Categories 
         filter = builder.Eq("Categories.Sub.id", id) & builder.Eq("Categories.Sub.Custom.id", subID); 
        else 
         //Get SubCategories 
         filter = builder.Eq("Categories.Sub.id", id); 
    else 
        //Get Generic Categories 
        filter = new BsonDocument(); 
    

    내가 검색 한 적이 있지만 아무도 : 일반적인 유형으로 설정

  • 새로운 BsonDocument로 설정
  • 또한이 내 코드입니다

오류를 발생합니다 오류가 발생합니다 내 문제가 있거나 찾지 못하는 것 같습니다.

답변

2

Var은 동적 변수가 아니므로 type inference의 키워드입니다. 이들은 매우 다른 개념입니다. 핵심 문제는 코드 스 니펫에서 컴파일러가 어떤 종류의 변수를 사용자가 var이 될지 파악할 수 없다는 것입니다.

var myNumber = 3; // myNumber is inferred by the compiler to be of type int. 

int myNumber = 3; // this line is considered by the computer to be identical to the one above. 

추정되는 var 변수의 유형은 변경되지 않습니다.

var myVariable = 3; 
myVariable = "Hello"; // throws an error because myVariable is of type int 

동적 변수의 타입 변화 할 수있다.

dynamic myVariable = 3; 
myVariable = "Hello"; // does not throw an error. 

필수가 VAR 변수를 생성하는 오브젝트의 종류를 판단 할 수 컴파일러; var 함께

var myVariable = null; // null can be anything, the compiler can not figure out what kind of variable you want. 

var myVariable = (BsonDocument)null; // by setting the variable to a null instance of a specific type the compiler can figure out what to set var to. 
+1

감사를 지정해야합니다! 타입'var'은 javascript 타입과 같았습니다. var에서 dynamic으로 형식을 변경 한 후 작동했습니다. – Gino

0

그것은 암시 형이고 그 값 타입과 참조 타입 둘 수 있기 때문에하면 null에 내재 형 변수를 초기화 할 수있다; 값 유형을 널 (NULL)에 지정할 수 없습니다 (달리 명시하지 않는 한 명시 적으로 널 (NULL) 입력 가능).

따라서 대신 var filter=null; 말의 명시 적 유형을

BsonDocument filter = null; 
+0

필터를'BsonDocument'로 설정하면 오류가 발생합니다.'filter = builder.Eq ("Categories.Sub.id", id);' 그것은 다른 타입을 반환합니다. – Gino

관련 문제