我尝试过关于这个主题的类似问题和答案,但我似乎无法找到(或理解)一个解决方案。
在表单1上,我有三个文本框,可以接收用户输入。在一个单独的类中,我有一个方法需要从这些文本框访问输入。
Form1.cs只包含文本框和一些按钮。另一个类中的方法是
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RealEstateApp
{
public class RealEstateApp : Form1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
const double RENTAL_AMOUNT = 1000.00;
RealEstateInvestment invest1 = new
RealEstateInvestment(2004, 150000, "65th Street");
invest1.MonthlyExpense = GetExpenses();
invest1.IncomeFromRent = RENTAL_AMOUNT;
invest1.DetermineMonthlyEarnings());
RealEstateInvestment invest2 = new
RealEstateInvestment("72 Westchester Dr.", 229000);
invest2.MonthlyExpense = 900;
invest2.IncomeFromRent = 1500.00;
}
public double GetExpenses()
{
double insurance;
double taxes;
double utilities;
string inValue;
inValue = txtBoxInsurance.Text; //Console.ReadLine(); (get user input from textbox)
insurance = double.Parse(inValue);
inValue = txtBoxTax.Text; //Console.ReadLine(); (get user input from textbox)
taxes = double.Parse(inValue);
inValue = txtBoxUtilities.Text; //Console.ReadLine(); (get user input from textbox)
utilities = double.Parse(inValue);
return (insurance / 12 + taxes / 12 + utilities);
}
}
}
由于我确信您已经注意到有c#人员,我遇到了错误&#39;非静态字段,方法或属性需要对象引用。&#39;
my static void Main()在第二个类中,如果它改变了什么。
修改的
我现在已经把整个班级代码放在上面,以便更好地了解正在发生的事情。
干杯,
马特
答案 0 :(得分:1)
将文本框的值传递给函数而不是文本框它会将您的类与表单类分离,您可以通过传递来自任何其他类的值来使用它。
定义
public static double GetExpenses(int pinsurance, int ptaxes, int putilities)
{
return (insurance / 12 + taxes / 12 + utilities);
}
呼叫
使用Int32.TryParse处理文本框中非int值的异常。
int insurance;
bool result = Int32.TryParse(txtBoxInsurance.Text, out insurance);
//Similarly you have to parse taxes and utilities
GetExpenses(insurance, taxes, utilities);
答案 1 :(得分:0)
我猜你得错了
inValue = txtBoxInsurance.Text;
这是因为您的GetExpenses()
方法属于静态类。其中txtboxInsurance
是类Form1
的私有和非静态属性。您无法从静态方法访问非静态方法属性。
相反,你可以做的是
public static class YourStaticClass
static string _insurance;
static string _tax;
static string _utilities;
public static double GetExpenses()
{ double insurance; double taxes; double utilities; string inValue; //Console.Write("Yearly Insurance: "); inValue = _insurance; //Console.ReadLine(); (get user input from textbox) insurance = double.Parse(inValue); //Console.Write("Yearly Tax: "); inValue = _tax; //Console.ReadLine(); (get user input from textbox) taxes = double.Parse(inValue); //Console.Write("Monthly Utilities: "); inValue = _utilities; //Console.ReadLine(); (get user input from textbox) utilities = double.Parse(inValue); return (insurance / 12 + taxes / 12 + utilities); }
并且
public partial class Form1 : Form
YourStaticClass._insurance=txtBoxInsurance.Text;
YourStaticClass._tax=txtBoxTax.Text;
YourStaticClass._utilities=txtBoxUtilities.Text;
我认为这应该有用