我有一个函数,它假设接收一个对象作为参数并使用其属性进一步使用,但是当我尝试访问对象属性时,它将它们标记为红色(无法解析符号......) 我试图添加一些参考,但它没有帮助。
public bool InsertStudent(object student)
{
var db = DAL.Services.SqlServicesPool.HackService;
using (var connection = db.StartConnection())
{
var sqlParam = new SqlParameter[]
{
new SqlParameter("@Name", student.Name),
new SqlParameter("@Lname", student.Lname),
new SqlParameter("@Phone", student.Phone),
new SqlParameter("@Email", student.Email),
new SqlParameter("@Img", student.Img),
new SqlParameter("@CityId", student.CityId)
};
var result = db.Exec(connection, "spInsertNewStudent", sqlParam);
db.StopConnection(connection);
return result;
};
}
答案 0 :(得分:3)
学生类型为object
,或更正式System.Object
。此类型没有任何名为Name
或Lname
等的属性。这就是问题所在。您应该将类型更改为用于创建学生对象的类。例如,如果您创建了如下所示的Student对象:
var student = new Student
{
Name = "foo"
// .....
}
您应该更改方法的签名,如下所示:
public bool InsertStudent(Student student)
答案 1 :(得分:0)
参数'student'具有'Object'类型。这是所有类和结构的基本类型。你应该把'学生'加入你的班级类型
public bool InsertStudent(object obj)
{
var student = (Student)obj;
....
}
或更改'student'参数类型
public bool InsertStudent(Student student)
{
....
}
答案 2 :(得分:0)
使用对象类的学生类
public bool InsertStudent(Student student)
{
var db = DAL.Services.SqlServicesPool.HackService;
using (var connection = db.StartConnection())
{
var sqlParam = new SqlParameter[]
{
new SqlParameter("@Name", student.Name),
new SqlParameter("@Lname", student.Lname),
new SqlParameter("@Phone", student.Phone),
new SqlParameter("@Email", student.Email),
new SqlParameter("@Img", student.Img),
new SqlParameter("@CityId", student.CityId)
};
var result = db.Exec(connection, "spInsertNewStudent", sqlParam);
db.StopConnection(connection);
return result;
};
}
public class Student
{
public string Name { get; set; }
public string Lname { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public byte []Img { get; set; }
public string CityId { get; set; }
}
或
public bool InsertStudent((Student)object student){ ... }
答案 3 :(得分:0)
正如Christos评论的那样,你需要使用Student对象。
public class Student
{
public string Name { get; set; }
public string Lname { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Image { get; set; } //Wasn't sure what type you use here
public int CityId { get; set; }
}
然后将Student对象作为参数传递。
public bool InsertStudent(Student student)
{
var db = DAL.Services.SqlServicesPool.HackService;
using (var connection = db.StartConnection())
{
var sqlParam = new SqlParameter[]
{
new SqlParameter("@Name", student.Name),
new SqlParameter("@Lname", student.Lname),
new SqlParameter("@Phone", student.Phone),
new SqlParameter("@Email", student.Email),
new SqlParameter("@Img", student.Img),
new SqlParameter("@CityId", student.CityId)
};
var result = db.Exec(connection, "spInsertNewStudent", sqlParam);
db.StopConnection(connection);
return result;
};
}